Map集合概述
-
Interface Map<K,V> K:键的类型;V:值的类型
-
将键映射到值的对象;不能包含重复的键;每个键可以映射到最多一个值
创建Map集合的对象
-
多态的方式
-
具体的实现类HashMap
Map集合基本功能
Map集合的获取功能
Map集合的遍历
方式一:获取键的集合,通过遍历集合的键,获取对应的值
public class MapDemo01 { public static void main(String[] args) { //创建集合对象 Map<String, String> map = new HashMap<>(); //V put(K key,V value)将制定的值与该映射中的指定键相关联 map.put("001","xiaoming"); map.put("002","xiaohuang"); map.put("003","xiaohong"); map.put("003","xiaolan"); Set<String> keyArr = map.keySet(); for(String s:keyArr){ System.out.println(s + ":" + map.get(s)); } } }
方式二:获取键值对对象的集合,遍历得到每一个键和值
public class MapDemo01 { public static void main(String[] args) { //创建集合对象 Map<String, String> map = new HashMap<>(); //V put(K key,V value)将制定的值与该映射中的指定键相关联 map.put("001", "xiaoming"); map.put("002", "xiaohuang"); map.put("003", "xiaohong"); map.put("003", "xiaolan"); //获取所有键值对对象的集合 Set<Map.Entry<String, String>> set = map.entrySet(); for (Map.Entry<String, String> me : set) { String key = me.getKey(); String value = me.getValue(); System.out.println(key + "," + value); } } }