Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap can keep always the same order? [duplicate]

I want to know if my HashMap collection will be always on the same order

        Map<Integer, Long> map = new HashMap<Integer, Long>(0);

        for(Integer key : users) {
            map.put( key , (long) 0 );
        }

        for( ... ){
            ...
            if( ... ) ){
                map.put( t.get(key) , map.get(key) + 1);
            }
        }

I send this collection to javascript with ajax

                    $.each( jsonData[i].totalMap , function(key, value) {
                        rows.push(value);
                    });

will have always the same order of the element of the Map as i put them in my controller ?

like image 942
Hayi Avatar asked Sep 13 '25 20:09

Hayi


2 Answers

If you use a LinkedHashMap, the order will be kept (i.e., by default, the keys will always be iterated in the same order they were inserted into the Map).

like image 53
Eran Avatar answered Sep 16 '25 11:09

Eran


If the keys and values are always the same, the map size is the same, and the HashMap is initialized in the same way, then yes. However for guaranteed iteration order, use a LinkedHashMap.

like image 36
Kayaman Avatar answered Sep 16 '25 09:09

Kayaman