ArrayList to HashMaps in Java - 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);
}

Related

TreeMap to Array. Does the array keep the order?

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.

Map - Fixed iteration order

Can we get data from a Map in some sequence or ordering which will be fixed for every time in Java?
Well in some maps you can. For example, any implementation of SortedMap (e.g. TreeMap) will return the entries sorted by key order (possibly according to a custom comparator) - although that has implications on the complexity of adding and fetching entries, of course.
Then there's LinkedHashMap which will always return entries in insertion order.
If you're talking about plain HashMap though - no, you mustn't rely on the ordering.
You can use the LinkedHashMap which is an ordered implementation of the Map interface.

How to avoid items being re-ordered when put into java HashMap

I'm creating a new Map and pushing strings into it (no big deal) -but I've noticed that the strings are being re-ordered as the map grows. Is it possible to stop this re-ordering that occurs so the items in the map retain the order the were put in with?
Map<String,String> x = new HashMap<String, String>();
x.put("a","b");
x.put("a","c");
x.put("a","d");
x.put("1","2");
x.put("1","3");
x.put("1","4");
//this shows them out of order sadly...
for (Map.Entry<String, String> entry : x.entrySet()) {
System.out.println("IN THIS ORDER ... " + entry.getValue());
}
If you care about order, you can use a SortedMap. The actual class which implements the interface (at least for most scenarios) is a TreeMap. Alternatively, LinkedHashMap also maintains its order, while still utilizing a hashtable-based container.
You can keep it with LinkedHashMap.
A HashMap in java is not sorted http://download.oracle.com/javase/1,5.0/docs/api/java/util/HashMap.html. If you want predictable iteration order use a LinkedHashMap instead: http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashMap.html
Heres a good discussion on the difference: How is the implementation of LinkedHashMap different from HashMap?
The previous answers are correct in that you should use an implementation of Map that maintains ordering. LinkedHashMap and SortedMap each do these things.
However, the takeaway point is that not all collections maintain order and if order is important to you, you should choose the appropriate implementation. Generic HashMaps do not maintain order, do not claim to do so and cannot be set to do so.

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.

What is the difference between a HashMap and a TreeMap? [duplicate]

This question already has answers here:
Difference between HashMap, LinkedHashMap and TreeMap
(17 answers)
Closed 8 years ago.
I started learning Java. When would I use a HashMap over a TreeMap?
TreeMap is an example of a SortedMap, which means that the order of the keys can be sorted, and when iterating over the keys, you can expect that they will be in order.
HashMap on the other hand, makes no such guarantee. Therefore, when iterating over the keys of a HashMap, you can't be sure what order they will be in.
HashMap will be more efficient in general, so use it whenever you don't care about the order of the keys.
HashMap is implemented by Hash Table while TreeMap is implemented by Red-Black tree. The main difference between HashMap and TreeMap actually reflect the main difference between a Hash and a Binary Tree , that is, when iterating, TreeMap guarantee can the key order which is determined by either element's compareTo() method or a comparator set in the TreeMap's constructor.
Take a look at following diagram.
To sum up:
HashMap: Lookup-array structure, based on hashCode(), equals() implementations, O(1) runtime complexity for inserting and searching, unsorted
TreeMap: Tree structure, based on compareTo() implementation, O(log(N)) runtime complexity for inserting and searching, sorted
Taken from: HashMap vs. TreeMap
Use HashMap most of the times but use TreeMap when you need the key to be sorted (when you need to iterate the keys).
I'll talk about the HashMap and TreeMap implementation in Java:
HashMap -- implement basic map interface
implemented by an array of buckets, each bucket is a LinkedList of entries
running time of basic operations: put(), average O(1), worst case O(n), happens when the table is resized; get(), remove(), average O(1)
not synchronized, to synchronize it: Map m = Collections.synchronizedMap(new HashMap(...));
Iteration order of the map is unpredictable.
TreeMap -- implement navigable map interface
implemented by a red-black tree
running time of basic operations: put(), get(), remove(), worst case O(lgn)
not synchronized, to synchronize it: SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
provide ordered iteration. higherKey(), lowerKey() can be used to get the successor and predecessor of a given key.
To sum, the biggest difference between HashMap and TreeMap is that TreeMap implements NavigableMap<K,V>, which provide the feature of ordered iteration. Besides, both HashMap and TreeMap are members of Java Collection framework. You can investigate the source code of Java to know more about their implementations.
You almost always use HashMap, you should only use TreeMap if you need your keys to be in a specific order.
HashMap is used for fast lookup, whereas TreeMap is used for sorted iterations over the map.
Along with sorted key store one another difference is with TreeMap, developer can give (String.CASE_INSENSITIVE_ORDER) with String keys, so then the comparator ignores case of key while performing comparison of keys on map access. This is not possible to give such option with HashMap - it is always case sensitive comparisons in HashMap.

Categories

Resources