Java 5种HashMap 的遍历方式
程序员文章站
2022-03-23 22:52:01
package mian;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry;public class Demo { public static void main(String[] args) { Map coursesMap = new HashMap
package mian;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class Demo {
public static void main(String[] args) {
Map<Integer,String> coursesMap = new HashMap<Integer, String>();
coursesMap.put(1,"c");
coursesMap.put(2,"c++");
coursesMap.put(3,"java");
coursesMap.put(4,"python");
// 1. 使用 Iterator 遍历 HashMap EntrySet
Iterator<Entry< Integer, String >> iterator = coursesMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry< Integer, String > entry = iterator.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
// 2. 使用 Iterator 遍历 HashMap KeySet
Iterator <Integer> iterator1 = coursesMap.keySet().iterator();
while (iterator1.hasNext()) {
Integer key = iterator1.next();
System.out.println(key);
System.out.println(coursesMap.get(key));
}
// 3. 使用 For-each 循环遍历 HashMap
for (Map.Entry < Integer, String > entry: coursesMap.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
// 4. 使用 Lambda 表达式遍历 HashMap
coursesMap.forEach((key, value) -> {
System.out.println(key);
System.out.println(value);
});
// 5. 使用 Stream API 遍历 HashMap
coursesMap.entrySet().stream().forEach((entry) -> {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
});
}
}
本文地址:https://blog.csdn.net/qq_39457143/article/details/110804757
下一篇: 两大推送服务---jpush和fcm