1, keySet way for loop:
Map<String, String> map = new HashMap<>();
map.put("A","a");
map.put("B","b");
map.put("C","c");
for (String key : map.keySet()) {
String value = map.get(key);
}
2, keySet the iterator iterator way:
Map<String, String> map = new HashMap<>();
map.put("A","a");
map.put("B","b");
map.put("C","c");
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
String value = map.get(iterator.next());
}
3, entrySet way for loop:
Map<String, String> map = new HashMap<>();
map.put("A","a");
map.put("B","b");
map.put("C","c");
for (Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}
4, entrySet the iterator iterator way:
Map<String, String> map = new HashMap<>();
map.put("A","a");
map.put("B","b");
map.put("C","c");
Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next().getKey();
String value = iterator.next().getValue();
}
to sum up:
- entrySet in its entirety is to be higher than keySet way;
- Simple access to key terms, the difference is not large, but if you want to get value, or efficiency entrySet would be better, because keySet need from the map again as key acquisition value, but once entrySet are all get out;
- iterator iterator way more efficient than the foreach.