Map 集合的遍历方式有 3 种:
方式一:键找值的方式遍历:先获取 Map 集合全部的键,再根据遍历键找值。
方式二:键值对的方式遍历,把“键值对“看成一个整体,难度较大。
方式三:JDK 1.8 开始之后的新技术:Lambda 表达式。
先通过 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);
}
}
复制代码
先通过 entrySet 方法把 Map 集合转换成 Set 集合,Set 集合中每个元素都是键值对实体类型了(将键和值看成一个整体)。
遍历获取到的 Set 集合,然后通过 getKey 提取键, 以及 getValue 提取值。
键值对设计到的 API:
Set
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);
}
}
复制代码
得益于 JDK 8 开始的新技术 Lambda 表达式,提供了一种更简单、更直接的遍历集合的方式。
Map 结合 Lambda 遍历的 API:
forEach(BiConsumer super K, ? super V> action) 结合 lambda 遍历 Map 集合
演示代码
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);
// 使用forEach方法遍历对象
maps.forEach(new BiConsumer
() { @Override
public void accept(String key, Integer value) {
System.out.println(key + "--->" + value);
}
});
}
复制代码
结合 Lambda 简化代码
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);
// 使用forEach方法集合Lambda表达式遍历对象
maps.forEach((key, value) -> System.out.println(key + "--->" + value));
}