If two hashmaps have exact same set of key-value pairs, will I always get data in same order while iterating on two hashmaps?
Map<String, String> map1 = new HashMap<>();
Map<String, String> map2 = new HashMap<>();
map1.put("a1","b1");
map1.put("a2","b2");
map1.put("a3","b3");
map2.put("a1","b1");
map2.put("a2","b2");
map2.put("a3","b3");
for (Map.Entry<String,String> e : map1.entrySet()) {
System.out.println(e.getKey());
}
for (Map.Entry<String,String> e : map2.entrySet()) {
System.out.println(e.getKey());
}
Run Code Online (Sandbox Code Playgroud)
If map1's iteration look like (a1,a2,a3), will map2's iteration also be like (a1,a2,a3)?
I know that bucket index is calculated using hash of key, but I am not sure if same index will be returned always.
小智 5
You can never rely on order in case of Hashmap.If you want to maintain insertion order use LinkedHashMap and for sorted order use TreeMap