通过检索,简单归纳了Map集合的五种遍历方式,根据需求选择。
获取键值对用ForEach循环
public static void main(String[] args) throws IOException {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 10);
map.put(2, 20);
// Iterating entries using a For Each loop
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
仅获取键/值
仅需key值或者value值的时候可以选择,不建议通过循环keySet()键集合的方法来遍历整个Map集合,会造成两次遍历,浪费性能。
public static void main(String[] args) throws IOException {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 10);
map.put(2, 20);
// Iterating over keys
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}
// Iterating over values
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}
}
使用带泛型的迭代器进行遍历
在JDK支持泛型的版本种可以选择
public static void main(String[] args) throws IOException {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 10);
map.put(2, 20);
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
使用不带泛型的迭代器进行遍历
在JDK不支持泛型的版本种可以选择
public static void main(String[] args) throws IOException {
Map map = new HashMap();
map.put(1, 10);
map.put(2, 20);
Iterator<Map.Entry> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Integer key = (Integer) entry.getKey();
Integer value = (Integer) entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
}
JDK 8 及以后版本 Lambda表达式
public static void main(String[] args) throws IOException {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 10);
map.put(2, 20);
map.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));
}