TreeMap to Array. Does the array keep the order? - java

For every time, if I put the same values to the treeMap, the order of data in treeMap will be the same, right? No matter VM etc? I want to find out, if I convert treeMap to array on following way, I get sorted array, for every time in the same order for fixed treeMap.
Map<String, String> treeMap = new TreeMap<String, String>();
treeMap.put("a","1");
...
treeMap.put("zzz","1000");
String[] myArray = treeMap.values().toArray(new String[treeMap.values().size()]);
If I execute above code I always receive the same value of myArray [100]? I assume that all keys are different.

Yes.
values() is documented as "in ascending order of the corresponding keys."
Collection.toArray() is documented as returning elements in iteration order, since there are ordering guarantees on the collection.

Related

Sorting collection in java

I have a HashMap which has keys as Date in Strings and value as an ArrayList of custom objects. I want to sort this hashmap on the basis of key. How can I do that?
HashMap<String,List<ClassName>> hashmap = new HashMap<String,List<ClassName>>();
When Hashmap is like this:
{"2015/07/15 : List("Object1","object2","object3")
"2015/07/14 :List("Object4" , "Object5")}
Please suggest.
You can use TreeMap instead of a HashMap . The TreeMap implements the Sorted Map interface.
As well as using a sorted map (as others have suggested) you can easily sort the keys when you use them rather than when you insert them.
For example, in Java 8:
treeMap.keySet().stream().sorted().forEach(System.out:println);
A nice thing about this is that it's easy to sort using different comparators without changing the collection.
For example, if you wanted to to sort by the number of items in the list value:
treeMap.keySet().stream().sorted(Comparator.comparingInt(k -> treeMap.get().size()))
This method is good for situations in which you insert and change values in the map often and then occasionally need the keys sorted for a particular operation. You get the performance of a HashMap but the flexibility to sort however you want on use.
You can use TreeMap, if you need the sorted map.
If you don't want to use TreeMap, then get the key and sort it as below.
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
map.put("2015/07/15", list);
map.put("2015/07/17", list1);
map.put("2015/07/16", list1);
ArrayList<String> keyset = new ArrayList<String>(map.keySet());
Collections.sort(keyset);
First thing is you can use TreeMap when you need a sorted map. However you are storing date value as Strings. Then it become harder to compare each. So i recommend to use java.util.Date instead of String. You can use a date formatter when you adding to the map. Use following code.
TreeMap<Date, List> treeMap = new TreeMap<>();
You can specify the Comparator in the constructor of the TreeMap. So it's easy to sort up things according to your custom order.

ArrayList to HashMaps in Java

I am trying to get values from an ArrayList that is sorted and want to store it in a HashMap, where the values of the ArrayList become keys of the HashMap. Will the order of the values in the HashMap still be the same as that of ArrayList?
No. Use a TreeMap instead. This will preserve the order of insertion.
HashMap makes no guarantees as to the order the mappings are stored or iterated, so simply running through the ArrayList and putting them into the HashMap as keys will very likely result in unordered iterations.
As others have pointed out, LinkedHashMap does preserve insertion order for iterations. An additional run of insertions will result in unordered iterations again, though. Both HashMap and LinkedHashMap support constant time lookup - LinkedHashMap pays for its extra feature in space (by maintaining pointers between the keys).
As others have also pointed out, TreeMap preserves order after updates, so this might be a better option for you, or not. Of course, if the ArrayList is sorted with a specific Comparator, you must feed that same Comparator to the TreeMap on construction for the sorting to be the same. Note that TreeMap does not have constant time lookup, due to being implemented as a Red-Black search tree.
As your ArrayList has been ordered, no need to use a TreeMap because this will compare to order again and it's not necessary. You should use a LinkedHashMap that will keep the exact order of your ArrayList when you put your value in.
Check This: Insert Values of ArrayList into HashMap
HashMap<String, Item> itemMap = new HashMap<String, Item>();
for (Item item : itemList)
{
itemMap.put(item.getitemCode(), item);
}

Multiple for loop on Java Set [duplicate]

This question already has answers here:
Is the order of values retrieved from a HashMap the insertion order
(6 answers)
Closed 9 years ago.
I have a Map with values and get a Set using Map.keySet method.
In this code:
Map<String, String> map = new HashMap<>();
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
Set<String> set = map.keySet();
for (int i = 0; i < 5; i++) {
for (String key : set) {
System.out.println(key);
}
}
am I guaranteed to get
1
2
3
written out every time? Where is this guarantee written down ? In Javadoc?
EDIT: Actually I don't care about the insertion order, but I care about the fact that using for-each loop on a set will produce the same result over and over, providing that the undelying map does not change (I don't call put, remove).
No, you are not. But you can use LinkedHashMap (http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html) and then you will be guaranteed.
LinkedHashMap for order of additionn (put), and TreeMap (interface SortedMap) for order of keys.
Unfortunately the docs for HashMap state that keySet() method does not return a SortedSet, it just returns a Set, for which the ordering is not guaranteed.
See HashMap.keySet()
Read, in particular: It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.
Use LinkedHashMap if you want to retrieve in order in which you put key .
No you're not guaranteed a specific order, unless you use a HashMap which implements a custom set that can give you this guarantee. The Set the HashMap gives you back have an Iterator() method which iterates over the elements in "no particular order".
Read the java documentation: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Set.html#iterator()
If you want the guarantee that the elements are iterated over in-order, i.e. ascending order, use something that implements SortedMap like TreeMap.
TreeMap Documentation: http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html
On this page you find the getSet() method which says "The set's iterator returns the keys in ascending order".

comparing hashmap data

I was wondering if it is possible to compare items in multiple hashMaps to each other:
HashMap<String,String> valueMap = new HashMap<String, String>();
HashMap<String,Integer> formulaMap = new HashMap<String, Integer>();
What I would basically like to do is something like:
if(the second string in valueMap is the same as the first string in formulaMap){
}
Is there a short way to achieve this or do I have to compare the strings before they are included into the hashMaps. My Integer at this stage of the program is required to take a null value. I can achieve my goals with a multi-dimensional array, but a solution like this would be more elegant and less time consuming.
By using a LinkedHashMap you can have a map that respects the insertion order of different values. Everything you have to do is iterate over the entrySet of the map until you reach the position you're looking for.
Plus: If you also need ordering, you can have a look at the TreeMap which inserts elements in order based on a criteria defined by you (You can pass a Comparator as a parameter for the map).
This order will apply to the keys of the map tough, so if you need value ordering you're going to have to come up with a little more complex solution (as in sorting the entry set directly and adding the values to another map, for example).

Java Map question

I have one Map that contains some names and numbers
Map<String,Integer> abc = new HashMap<String,Integer>();
It works fine. I can put some values in it but when I call it in different class it gives me wrong order. For example:
I putted
abc.put("a",1);
abc.put("b",5);
abc.put("c",3);
Iterator<String> iter = abc.keySet().iterator();
while (iter.hasNext()) {
String name = iter.next();
System.out.println(name);
}
some time it returns the order (b,a,c) and some time (a,c,b).
What is wrong with it? Is there any step that I am missing when I call this map?
Edit:
I changed to HashMap and result is still same
The only thing that's wrong is your expectations. The Map interface makes no guarantees about iteration order, and the HashMap implementation is based on hash functions which means the iteration order is basically random, and will sometimes change completely when new elements are added.
If you want a specific iteration order, you have thee options:
The SortedMap interfaces with its TreeMap implementation - these guarantee an iteration order according to the natural ordering of the keys (or an ordering imposed by a Comparator instance)
The LinkedHashMap class iterates in the order the elements were added to the map.
Use a List instead of a Map - this has a well-defined iteration order that you can influence in detail.
I think you need LinkedHashMap.
A TreeMap will always have keys in their natural order (unless you provide a comparator) If you are seeing the order any differently it will be the way you are looking at the map and what you are doing with it. If in doubt, use a debugger and you will see the order is sorted.
If you wish to get map values in the same order you used to insert them use LinkedHashMap instead.

Categories

Resources