package com.bt.springboot.demo;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* @author
* @Date 2022/5/18 15:59
*/
public class HashMapDemo {
public static void main(String[] args) {
HashMap<String,Object> map = new HashMap();
map.put("张三","zs");
map.put("李四","ls");
map.put("王五","ww");
// 遍历map
// 1.EntrySet遍历
for(Map.Entry<String,Object> entry:map.entrySet()){
System.out.println(entry.getKey() + ":" + entry.getValue());
}
System.out.println("---------------");
// 2.KeySet遍历 性能不如EntrySet (不建议使用)
for(String key : map.keySet()){{
System.out.println(key + ":" + map.get(key));
}}
System.out.println("---------------");
// 3.使用迭代器遍历 迭代器的作用是可以在遍历代码时动态删除元素
Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String, Object> entry = iterator.next();
if("张三".equals(entry.getKey())){
iterator.remove();
continue;
}
System.out.println(entry.getKey() + ":" + entry.getValue());
}
System.out.println("---------------");
// 4.JDK8之后的遍历
map.forEach((key,value) ->{
System.out.println(key + ":" + value);
});
// 5.stream多线程遍历 效率高
System.out.println("---------------");
map.entrySet().stream().parallel().forEach((entry) ->{
System.out.println(entry.getKey() + ":" + entry.getValue());
});
}
}
Java遍历map集合的几种方式
于 2022-05-18 16:41:48 首次发布