Python 官方文档:入门教程 => 点击学习
目录Map 集合的遍历方式有 3 种:Map 集合的遍历方式一: 键找值键找值涉及到的 api:Map 集合的遍历方式二: 键值对键值对设计到的 API:Map 集合的遍历方式三:
方式一:键找值的方式遍历:先获取 Map 集合全部的键,再根据遍历键找值。
方式二:键值对的方式遍历,把“键值对“看成一个整体,难度较大。
方式三:jdk 1.8 开始之后的新技术:Lambda 表达式。
先通过 keySet 方法, 获取 Map 集合的全部键的 Set 集合。
遍历键的 Set 集合,然后通过键提取对应值。
keySet() 获取所有键的集合
get(Object key) 根据键获取值
演示代码
public static void main(String[] args) {
Map<String, Integer> 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<String> keys = maps.keySet();
// 遍历键, 根据键获取值
for (String key: keys) {
int value = maps.get(key);
System.out.println(key + "--->" +value);
}
}
先通过 entrySet 方法把 Map 集合转换成 Set 集合,Set 集合中每个元素都是键值对实体类型了(将键和值看成一个整体)。
遍历获取到的 Set 集合,然后通过 geTKEy 提取键, 以及 getValue 提取值。
Set<Map.Entry<K,V>> entrySet() 获取所有键值对对象的集合
getKey() 获得键
getValue() 获取值
演示代码
public static void main(String[] args) {
Map<String, Integer> 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<Map.Entry<String, Integer>> newMaps = maps.entrySet();
// 遍历转成的Set集合
for (Map.Entry<String, Integer> newMap : newMaps) {
String key = newMap.getKey(); // 获取key
Integer value = newMap.getValue(); // 获取value
System.out.println(key + "--->" + value);
}
}
得益于 JDK 8 开始的新技术 Lambda 表达式,提供了一种更简单、更直接的遍历集合的方式。
forEach(BiConsumer<? super K, ? super V> action) 结合 lambda 遍历 Map 集合
演示代码
public static void main(String[] args) {
Map<String, Integer> 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<String, Integer>() {
@Override
public void accept(String key, Integer value) {
System.out.println(key + "--->" + value);
}
});
}
public static void main(String[] args) {
Map<String, Integer> 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));
}
到此这篇关于Java 中 Map 集合的三种遍历方式的文章就介绍到这了,更多相关Java 中 Map 集合遍历内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Java中Map集合的三种遍历方式小结
本文链接: https://www.lsjlt.com/news/175826.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0