【Java基础】Map遍历的5种方式
目录
创建一个集合
方式一:Iterator 迭代器遍历
map.entrySet().iterator();
map.keySet().iterator();
方式二:For Each方式遍历
map.forEach(BiConsumer action)
方式三:获取Collection集合
map.values().forEach()
方式四:增强for遍历map
map.entrySet().for
map.keySet().for
方法五:Stream流遍历
map.entrySet().stream().forEach()
map.keySet().stream().forEach()
💟 创作不易,不妨点赞💚评论❤️收藏💙一下
创建一个集合
HashMap<Integer, String> map = new HashMap<>();map.put(1,"ljj");map.put(2,"zsy");map.put(3,"sxf");map.put(4,"wjx");}
方式一:Iterator 迭代器遍历
map.entrySet().iterator();
map.keySet().iterator();
//Iterator 迭代器遍历public static void iterator(Map<Integer, String> map){System.out.println("---使用entrySet()迭代器进行遍历map集合---");Iterator<Map.Entry<Integer, String>> entryIterator = map.entrySet().iterator();while (entryIterator.hasNext()){Map.Entry<Integer, String> entry = entryIterator.next();System.out.println(entry.getKey()+":"+entry.getValue());}System.out.println("---使用KeySet()迭代器进行遍历map集合---");Iterator<Integer> keySetIterator = map.keySet().iterator();while (keySetIterator.hasNext()){Integer key = keySetIterator.next();System.out.println(key+":"+map.get(key));}}
方式二:For Each方式遍历
map.forEach(BiConsumer action)
//For Each方式遍历public static void forEach_map(Map<Integer,String> map){System.out.println("map.forEach(BiConsumer action)方法遍历map");map.forEach((key,value) -> System.out.println(key+" : "+value));}
方式三:获取Collection集合
map.values().forEach()
map中的values()方法,通过这个方法可以直接获取Map中存储所有值的Collection集合
//values()方法public static void Collection_forEach(Map<Integer,String> map){System.out.println("获取map集合的values值集合对象,进行forEach遍历");//Map中的values()方法,通过这个方法可以直接获取Map中存储所有值的Collection集合Collection<String> values = map.values();values.forEach( v -> System.out.println(v));}
方式四:增强for遍历map
map.entrySet().for
map.keySet().for
public static void for_plus(Map<Integer,String> map){System.out.println("增强for循环,Map.Entry<>");for (Map.Entry<Integer,String> entry : map.entrySet()){String value = entry.getValue();System.out.println(value);}System.out.println("增强for循环,map.keySet");for (Integer key : map.keySet()){String value = map.get(key);System.out.println(value);}}
方法五:Stream流遍历
map.entrySet().stream().forEach()
map.keySet().stream().forEach()
//Stream流遍历public static void stream_list(Map<Integer,String> map){System.out.println("map.entrySet().stream.forEach()遍历—Stream流遍历");map.entrySet().stream().forEach((Map.Entry<Integer,String> entry) -> {System.out.print(entry.getKey()+":");System.out.println(entry.getValue());});System.out.println("map.keySet().stream.forEach()遍历—Stream流遍历");map.keySet().stream().forEach(key -> {System.out.println(map.get(key));});}
写到最后
四季轮换,已经数不清凋零了多少, 愿我们往后能向心而行,一路招摇胜!
🐋 你的支持认可是我创作的动力
💟 创作不易,不妨点赞💚评论❤️收藏💙一下
😘 感谢大佬们的支持,欢迎各位前来不吝赐教