Java中Map集合的三种遍历方式 |
您所在的位置:网站首页 › map集合的遍历方法 › Java中Map集合的三种遍历方式 |
文章目录
Map集合的遍历方式Map集合的遍历方式一: 键找值Map集合的遍历方式二: 键值对Map集合的遍历方式三: Lambda
Map集合的遍历方式
Map集合的遍历方式有3种: 方式一:键找值的方式遍历:先获取Map集合全部的键,再根据遍历键找值。 方式二:键值对的方式遍历,把“键值对“看成一个整体,难度较大。 方式三:JDK 1.8开始之后的新技术:Lambda表达式。 Map集合的遍历方式一: 键找值先通过keySet方法, 获取Map集合的全部键的Set集合。 遍历键的Set集合,然后通过键提取对应值。 键找值涉及到的API: 方法名称说明keySet()获取所有键的集合get(Object key)根据键获取值演示代码: public static void main(String[] args) { Map maps = new HashMap(); maps.put("华为", 10); maps.put("小米", 5); maps.put("iPhone", 6); maps.put("生活用品", 15); maps.put("java", 20); maps.put("python", 17); // 拿到全部集合的全部键 Set keys = maps.keySet(); // 遍历键, 根据键获取值 for (String key: keys) { int value = maps.get(key); System.out.println(key + "--->" +value); } } Map集合的遍历方式二: 键值对先通过entrySet方法把Map集合转换成Set集合,Set集合中每个元素都是键值对实体类型了(将键和值看成一个整体)。 遍历获取到的Set集合,然后通过getKey提取键, 以及getValue提取值。 键值对设计到的API: 方法名称说明Set entrySet()获取所有键值对对象的集合getKey()获得键getValue()获取值演示代码: public static void main(String[] args) { Map maps = new HashMap(); maps.put("华为", 10); maps.put("小米", 5); maps.put("iPhone", 6); maps.put("生活用品", 15); maps.put("java", 20); maps.put("python", 17); // 把Map集合转成Set集合 Set newMaps = maps.entrySet(); // 遍历转成的Set集合 for (Map.Entry newMap : newMaps) { String key = newMap.getKey(); // 获取key Integer value = newMap.getValue(); // 获取value System.out.println(key + "--->" + value); } } Map集合的遍历方式三: Lambda得益于JDK 8开始的新技术Lambda表达式,提供了一种更简单、更直接的遍历集合的方式。 Map结合Lambda遍历的API: 方法名称说明forEach(BiConsumer |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |