# iteration Java HashMap的keySet（）迭代順序是否一致？

java iteration hashmap hashset

``````Map<K,V> map = getMap();

for( K k : map.keySet() )
{
}

...

for( K k : map.keySet() )
{
}
``````

Hashmap不保證地圖的順序會隨著時間的推移保持不變。

``````HashMap<Integer, String> map;

@Before
public void initData() {
map = new HashMap<>();

map.put(55, "John");
map.put(22, "Apple");
map.put(66, "Earl");
map.put(77, "Pearl");
map.put(12, "George");
map.put(6, "Rocky");

}
``````

``````public void showMap (Map<Integer, String> map1) {
for (Map.Entry<Integer,  String> entry: map1.entrySet()) {
System.out.println("[Key: "+entry.getKey()+ " , "+"Value: "+entry.getValue() +"] ");

}

}
``````

``````Map before sorting :
[Key: 66 , Value: Earl]
[Key: 22 , Value: Apple]
[Key: 6 , Value: Rocky]
[Key: 55 , Value: John]
[Key: 12 , Value: George]
[Key: 77 , Value: Pearl]
``````

``````    List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());

Collections.sort(entries, new Comparator<Entry<Integer, String>>() {

@Override
public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {

return o1.getKey().compareTo(o2.getKey());
}
});

HashMap<Integer, String> sortedMap = new LinkedHashMap<>();

for (Map.Entry<Integer, String> entry : entries) {
System.out.println("Putting key:"+entry.getKey());
sortedMap.put(entry.getKey(), entry.getValue());
}

System.out.println("Map after sorting:");

showMap(sortedMap);
``````

``````Sorting by keys :
Putting key:6
Putting key:12
Putting key:22
Putting key:55
Putting key:66
Putting key:77
Map after sorting:
[Key: 66 , Value: Earl]
[Key: 6 , Value: Rocky]
[Key: 22 , Value: Apple]
[Key: 55 , Value: John]
[Key: 12 , Value: George]
[Key: 77 , Value: Pearl]
``````

``````    HashMap<Integer, String> sortedMap = new LinkedHashMap<>();

for (Map.Entry<Integer, String> entry : entries) {
System.out.println("Putting key:"+entry.getKey());
sortedMap.put(entry.getKey(), entry.getValue());
}

System.out.println("Map after sorting:");

showMap(sortedMap);
``````

``````Sorting by keys :
Putting key:6
Putting key:12
Putting key:22
Putting key:55
Putting key:66
Putting key:77
Map after sorting:
[Key: 6 , Value: Rocky]
[Key: 12 , Value: George]
[Key: 22 , Value: Apple]
[Key: 55 , Value: John]
[Key: 66 , Value: Earl]
[Key: 77 , Value: Pearl]
``````

### Tags

java   iteration   hashmap   hashset