通过ForEach循环遍历
//foreach
public static void traversal1(Map<?, ?> map) {
for (Map.Entry<?, ?> entry : map.entrySet()) {
System.out.print(entry.getKey() + ":" + entry.getValue() + " ");
}
System.out.println();
}
//
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("bobo", 5);
map.put("pengpeng", 8);
map.put("tangtang", 3);
map.put("songsong", 9);
map.put("miaomiao", 4);
traversal1(map);
}
forEach迭代遍历
//foreach迭代键值对
public static void traversal2(Map<String, Integer> map) {
for (String key : map.keySet()) {
System.out.print(key + " ");
}
System.out.println();
for(Integer key : map.values()) {
System.out.print(key + " ");
}
System.out.println();
}
使用迭代器进行遍历
//使用迭代器进行遍历
public static void traversal3(Map<String, Integer> map) {
Iterator<Map.Entry<String, Integer>> entries = map.entrySet().iterator();
while(entries.hasNext()) {
Map.Entry<String, Integer> entry = entries.next();
System.out.print(entry.getKey() + ":" + entry.getValue() + " ");
}
System.out.println();
}
使用不带泛型的迭代器遍历
//使用不带泛型的迭代器遍历
public static void staversal4(Map map) {
Iterator<Map.Entry> entries = map.entrySet().iterator();
while(entries.hasNext()) {
Map.Entry entry = entries.next();
System.out.print(entry.getKey() + ":" + entry.getValue() + " ");
}
System.out.println();
}
通过Lambda表达式进行遍历
//通过Lambda表达式进行遍历
public static void traversal5(Map map) {
map.forEach((k, v) -> System.out.print(k + ":" + v + " "));
}