Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating HashMap on order it has been set

I've set a HashMap on certain order but it is iterated on a strange order!

Please consider code below:

HashMap<String, String> map = new HashMap<String, String>();
map.put("ID", "1");
map.put("Name", "the name");
map.put("Sort", "the sort");
map.put("Type", "the type");

...

for (String key : map.keySet()) {
    System.out.println(key + ": " + map.get(key));
}

and the result:

Name: the name
Sort: the sort
Type: the type
ID: 1

I need to iterate it in order i've put the entries. Any help will be appreciated.

like image 765
AHHP Avatar asked Dec 15 '12 16:12

AHHP


People also ask

Does HashMap iterate in order?

In Java, one of the most commonly-used data structures is the HashMap . Unlike LinkedHashMap (insertion-order) and TreeMap (key-based order), HashMap does not provide any guarantees of ordering when iterating over the map, e.g. when using a for-each loop, or calling forEach() .

Are HashMap Keys ordered?

As we know that Hash map in Java does not maintain insertion order either by key or by order. Also it does not maintain any other order while adding entries to it.

Is HashMap automatically sorted?

No, HashMap s don't sort their keys automatically. You want a TreeMap for sorting the keys, or a LinkedHashMap to retain the insertion order.


2 Answers

That's how HashMap works internally. Replace HashMap with LinkedHashMap which additionally remembers the order of insertion:

Map<String, String> map = new LinkedHashMap<String, String>();
like image 200
Tomasz Nurkiewicz Avatar answered Oct 17 '22 04:10

Tomasz Nurkiewicz


The order depends on the result of the hashCode() function in the keys you are inserting which, unless you did something strange, is going to be mostly random (but consistent). What you are looking for is a sorted map such as a LinkedHashMap

Check out a little bit about how hashtables work here if you are interested in the details.

like image 28
Miquel Avatar answered Oct 17 '22 04:10

Miquel