目录
一、通过KeySet()方法遍历
先通过map.keySet()获取所有键,然后遍历所有键获取对应值,具体代码如下:
public class Test {
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);
map.put("c",3);
map.put("d",4);
//方法一:通过keySet()遍历
// 1.1 增强for循环遍历
Set<String> keys = map.keySet();
for(String s: keys){
System.out.println("key="+s+" "+"value="+map.get(s));
}
// 1.2 iterator遍历
System.out.println("iterator遍历...");
Iterator<String> i = keys.iterator();
while (i.hasNext()){
String key=i.next();
System.out.println("key="+key+" "+"value="+map.get(key));
}
}
}
二、通过entrySet()方法遍历
map.entrySet()方法返回键值对映射的Set集合,然后遍历这个集合即可。具体代码如下:
public class Test {
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);
map.put("c",3);
map.put("d",4);
//方法二:通过entrySet()方法遍历
for(Map.Entry<String,Integer> m: map.entrySet()){
System.out.println("key="+m.getKey()+" "+"value="+m.getValue());
}
}
}
三、通过Lambda表达式遍历
JDK1.8之后支持Lambda表达式,具体代码如下:
public class Test {
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);
map.put("c",3);
map.put("d",4);
//方法三:通过Lambda表达式遍历
map.forEach((key, value) -> {
System.out.println("key="+key+" "+"value="+value);
});
}
}
四、通过Streams遍历
JDK1.8之后支持Streams,具体代码如下:
public class Test {
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);
map.put("c",3);
map.put("d",4);
//方法四:通过Streams遍历
// 4.1 单线程
map.entrySet().stream().forEach((entry) -> {
System.out.println("key="+entry.getKey()+" "+"value="+entry.getValue());
});
// 4.2 多线程
System.out.println("Streams API多线程...");
map.entrySet().parallelStream().forEach((entry) -> {
System.out.println("key="+entry.getKey()+" "+"value="+entry.getValue());
});
}
}
除了 Stream 的并行循环,其他几种遍历方法的性能差别不大,但从简洁性和优雅性上来看,Lambda 和 Stream无疑是最适合的遍历方式。