Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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());
}
like image 820
Toran Billups Avatar asked Sep 06 '11 19:09

Toran Billups


1 Answers

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.

like image 89
dlev Avatar answered Oct 14 '22 16:10

dlev