目标:Map集合的遍历
Map集合的遍历方式:
(1)键找值的方式遍历:先拿到Map集合所有的键,再遍历键获取对应的值。(简单的)
(2)键值对方式遍历。(最复杂,最难理解,老程序喜欢用的。更面向对象的做法!)
(3)JDK 1.8开始的新技术Lambda表达式遍历Map集合(非常的简单了,可以普遍使用了)
1.键找值的方式遍历:先拿到Map集合所有的键,再通过遍历键获取对应值。(最简单的)
public class MapDemo01 {
public static void main(String[] args) {
Map<String,Integer> maps = new HashMap<>();
// 1.添加元素:添加键值对元素
maps.put("iphoneX" , 1);
maps.put("娃娃" , 8);
maps.put("huawei" , 8);
maps.put("Java" , 1);
System.out.println(maps);
// maps = {huawei=8, Java=1, iphoneX=1, 娃娃=8}
// a.先提取map集合全部的键到一个Set集合中去
Set<String> keys = maps.keySet(); // [huawei , Java , iphoneX , 娃娃]
// b.再通过遍历键获取对应值。
for(String key : keys){
// 根据键取出对应的值
Integer value = maps.get(key);
System.out.println(key+"---->"+value);
}
}
}
2.键值对方式遍历
public class MapDemo02 {
public static void main(String[] args) {
Map<String,Integer> maps = new HashMap<>();
// 1.添加元素:添加键值对元素
maps.put("iphoneX" , 1);
maps.put("娃娃" , 8);
maps.put("huawei" , 8);
maps.put("Java" , 1);
System.out.println(maps);
/**
maps = {huawei=8, Java=1, iphoneX=1, 娃娃=8}
最开始是想直接用foreach遍历Map集合
发现foreach根本不能直接遍历Map集合,Map集合的键值对元素直接来看是没有类型的。
|
把Map集合转换成Set集合:Set<Map.Entry<K, V>> entrySet();
|
Set<Map.Entry<String,Integer>> entries = maps.entrySet();
entries = [ (huawei=8), (Java=1), (iphoneX=1), (娃娃=8)]
entry
此时里面的键值对元素(huawei=8)变成了一个对象,有了类型,类型是:Map.Entry<String,Integer>
*/
Set<Map.Entry<String, Integer>> entries = maps.entrySet();
for(Map.Entry<String,Integer> entry : entries){
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key +"---->"+value);
}
}
}
3.JDK 1.8开始的新技术(普遍使用了),真的好简单!(了解)
public class MapDemo03 {
public static void main(String[] args) {
Map<String,Integer> maps = new HashMap<>();
// 1.添加元素:添加键值对元素
maps.put("iphoneX" , 1);
maps.put("娃娃" , 8);
maps.put("huawei" , 8);
maps.put("Java" , 1);
System.out.println(maps);
// maps = {huawei=8, Java=1, iphoneX=1, 娃娃=8}
maps.forEach((k , v) -> {
System.out.println(k +"--->"+v);
});
}
}