Reputation: 1820
I have input data (Timestamp, Json string) which I store in a HashMap<Long, String>
. To process the JSON string I use an iterator.
I use Iterator<Entry<Long, String>> it = data.entrySet().iterator();
to get the entrySet as iterator.
My problem is now that the HashMap is organized as follows:
123,{String1}
124,{String2}
125,{String3}
Better expressed: I add A to the HashMap, Z to the HashMap, E to the HashMap, I to the HashMap. I expect the order A, Z, E, I and I want the same order in the iterator.
If I put it in an iterator I get:
124, {String2}
123, {String1}
125, {String3}
The order of the itarator is different from the HashMap order. For me the order of the iterator has to be exactly the same as the order of the HashMap. What I'm doing wrong, that the iterator is changing the order of the data?
Upvotes: 1
Views: 1041
Reputation: 1022
Additional to the above findings,
Even you can use LinkedHashMap as given below,LinkedHashMap will make sure values stored in the order of insertion.
public static void main(String[] args) {
Map<Integer, String> map = new LinkedHashMap<Integer, String>();
Map<Integer, String> map2 = new HashMap<Integer, String>();
map.put(1, "oneone");
map.put(3, "twoone");
map.put(2, "threeone");
map2.put(1, "oneone");
map2.put(3, "twoone");
map2.put(2, "threeone");
for(Entry<Integer, String> entry:map.entrySet()){
System.out.println(entry.getKey());
}
for(Entry<Integer, String> entry:map2.entrySet()){
System.out.println(entry.getKey());
}
}
Here result will be,
1
3
2
1
2
3
Upvotes: 2
Reputation: 18153
Excerpt from the java.util.Map
API doc: "The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not."
Upvotes: 1
Reputation: 41955
HashMap documentation says that
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
So you should not rely on the order while you are iterating views entrySet
or keySet
or values
.
Some implementations of Map
such as TreeMap
provide ordering guarantee as @Oleg S and @Smutje have already suggested.
Upvotes: 1
Reputation: 10082
HashMap
is not organised in any particular order, or more precisely, the order is not guaranteed. If you want an ordered map, use SortedMap
with a TreeMap
implementation providing a Comparator
if you need to override the default ordering of keys.
Upvotes: 3