// 第一种方法,foreach keySet
for (Integer key : testMap.keySet()) {
System.out.print(key + "-" + testMap.get(key) + " ");
}
// 第二种方法,foreach values
for (String value : testMap.values()) {
System.out.print(value + " ");
}
// 第三种方法,foreach entrySet
for (Map.Entry<Integer, String> entry : testMap.entrySet()) {
System.out.print(entry.getKey() + "-" + entry.getValue() + " ");
}
// 第四种方法,entrySet iterator
Iterator<Map.Entry<Integer, String>> it = testMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
System.out.print(entry.getKey() + "-" + entry.getValue() + " ");
}
(值得注意的是,这种方法无法改变变量的值,会提示Variable used in lambda expression should be final or effectively final)
// 第五种方法,Map的forEach方法,Java8独有
testMap.forEach((key, value) -> {
System.out.print(key + "-" + value + " ");
});
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MapTest {
public static void main(String[] args) {
HashMap<Integer, String> testMap = new HashMap<>();
testMap.put(1, "One");
testMap.put(2, "Two");
testMap.put(3, "Three");
testMap.put(4, "Four");
testMap.put(5, "Five");
// 第一种方法,foreach keySet
for (Integer key : testMap.keySet()) {
System.out.print(key + "-" + testMap.get(key) + " ");
}
System.out.println("
foreach keySet");
// 第二种方法,foreach values
for (String value : testMap.values()) {
System.out.print(value + " ");
}
System.out.println("
foreach values");
// 第三种方法,foreach entrySet
for (Map.Entry<Integer, String> entry : testMap.entrySet()) {
System.out.print(entry.getKey() + "-" + entry.getValue() + " ");
}
System.out.println("
foreach entrySet");
// 第四种方法,entrySet iterator
Iterator<Map.Entry<Integer, String>> it = testMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
System.out.print(entry.getKey() + "-" + entry.getValue() + " ");
}
System.out.println("
entrySet iterator");
// 第五种方法,Map的forEach方法,Java8独有
testMap.forEach((key, value) -> {
System.out.print(key + "-" + value + " ");
});
System.out.println("
Map.forEach()");
}
}
1-One 2-Two 3-Three 4-Four 5-Five
foreach keySet
One Two Three Four Five
foreach values
1-One 2-Two 3-Three 4-Four 5-Five
foreach entrySet
1-One 2-Two 3-Three 4-Four 5-Five
entrySet iterator
1-One 2-Two 3-Three 4-Four 5-Five
Map.forEach()