遍历HashMap的七种方法"/>
遍历HashMap的七种方法
直接上代码
/*** @Description* @Author 暴怒阿西* @Date 2022-11-15 15:22*/
public class HashMapTest2 {static HashMap<Integer, String> map = new HashMap<>();static {map.put(1, "Java");map.put(2, "PHP");map.put(3, "C#");map.put(4, "Golang");}//使用 iterator 遍历EntrySet@Testpublic void test1() {Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();while (iterator.hasNext()) {Map.Entry<Integer, String> entry = iterator.next();System.out.print(entry.getKey()+" ");System.out.println(entry.getValue());}}//使用 iterator 遍历KeySet@Testpublic void test2() {Iterator<Integer> iterator = map.keySet().iterator();while (iterator.hasNext()) {Integer key = iterator.next();System.out.print(key+" ");System.out.println(map.get(key));}}// forEach keySet@Testpublic void test3() {Set<Integer> keySet = map.keySet();for (Integer key : keySet) {System.out.print(key+" ");System.out.println(map.get(key));}}// forEach EntrySet@Testpublic void test4() {Set<Map.Entry<Integer, String>> entries = map.entrySet();for (Map.Entry<Integer, String> entry : entries) {System.out.print(entry.getKey()+" ");System.out.println(entry.getValue());}}// Lambda forEach@Testpublic void test5() {map.forEach((k,v)->{System.out.print(k+" ");System.out.println(v);});}//Streams 单线程@Testpublic void test6() {map.entrySet().stream().forEach((entry)->{System.out.print(entry.getKey()+" ");System.out.println(entry.getValue());});}//Stream 多线程@Testpublic void test7() {map.entrySet().parallelStream().forEach((entry)->{System.out.print(entry.getKey()+" ");System.out.println(entry.getValue());});}
}
更多推荐
遍历HashMap的七种方法
发布评论