Map双列集合的四种遍历方式
第一种:键找值遍历方式
- 通过keySet()方法可以获取到所有键组成的Set集合。
-
public Set<K> keySet(): 获取所有键组成的Set集合
-
遍历Set集合获取到每一个键之后,通过get方法获取到对应的值。
案例:
public class MapDemo3 { public static void main(String[] args) { HashMap<String, String> students = new HashMap<>(); students.put("小三","北京市昌平区"); students.put("小四","北京市昌平区"); students.put("小五","北京市海淀区"); students.put("小六","北京市门头沟区"); //Map遍历方式(1):键找值:获取所有键,在通过键找值 //1、获取到所有键组成的set集合 keySet方法 Set<String> keys = students.keySet(); //2、遍历Set集合获取每一个键,通过get方法获取值 for (String key : keys) { String value = students.get(key); System.out.println("[key]:"+key+" [value]:"+value); } } }
第二种:键值对遍历方式(重点)
-
通过entrySet方法可以获取到所有键值对对象组成的Set集合。
-
public Set<Map.Entry<K,V>> entrySet() : 获取所有键组成的Set集合
-
-
遍历Set集合获取每一个键值对对象之后可以通过键值对对象的方法获取里面封装的键与值。
-
public K getKey() : 获取键值对中的键 public V getValue() : 获取键值对中的值
案例:
public class MapDemo4 { public static void main(String[] args) { HashMap<String, String> students = new HashMap<>(); students.put("小三", "北京市昌平区"); students.put("小四", "北京市昌平区"); students.put("小五", "北京市海淀区"); students.put("小六", "北京市门头沟区"); //Map的遍历方式(2):键值对 获取所有键值对对象之后,遍历获取到每一个键值对对象,在获取key和value //1、entrySet方法获取所有的键值对对象 注意:调用方法之后自然返回值即可 Set<Map.Entry<String, String>> entrySet = students.entrySet(); for (Map.Entry<String, String> entry : entrySet) { String key = entry.getKey(); String value = entry.getValue(); System.out.println("key:"+key+" value:"+value); } } }
-
第三种:获取所有值方式
-
Map中的提供了获取所有值的方法,但是此方法只可以获取到所有的值,无法通过值获取到键。
-
通过values方法可以获取到所有值组成的集合
-
public Collection<V> values() : 获取所有值组成的Collection集合。 //因为值会重复所以返回的是Collection集合
案例:
public class MapDemo5 { public static void main(String[] args) { HashMap<String, String> students = new HashMap<>(); students.put("小三", "北京市昌平区"); students.put("小四", "北京市昌平区"); students.put("小五", "北京市海淀区"); students.put("小六", "北京市门头沟区"); //Map遍历方式(3):获取所有值 Collection<String> values = students.values(); System.out.println("values:"+values); } }
-
第四种:Java8的foreach遍历方式(函数式编程思想 重点)
-
实际上Map提供了一个方法,可以自动完成Map的遍历,开发者需要提供的就是如何使用获取到的键与值。
-
函数式编程思想:不管怎么去做(不管怎么获取键和值),而是强调去做什么(键和值要去怎么用)。
-
public void foreach(BiConsumer<K,V> consumer) : 按照指定的逻辑使用Map中的每一个键值
案例:
public class MapDemo6 { public static void main(String[] args) { HashMap<String, String> students = new HashMap<>(); students.put("小三", "北京市昌平区"); students.put("小四", "北京市昌平区"); students.put("小五", "北京市海淀区"); students.put("小六", "北京市门头沟区"); //Map的遍历方式(4):foreach[函数式编程] //1、调用foreach方法,在方法的参数中传递BiConsumer接口的实现对象,实现accept(消费键值的方法) //使用的是匿名内部类。 students.forEach(new BiConsumer<String, String>() { //参数1:键 参数2:值 //实现accept方法 @Override public void accept(String key, String value) { //accept方法中Map会自动获取到的每一个键,值作为参数传递(通过key+value去做什么) System.out.println("key:"+key+" value:"+value); } }); } }
-