1.Map概述
1.map集合中有 建 ,建头有个对应的值(映射),
一个映射不能包含重复的键
每个键最多只能映射到一个值
2.Map和Collection接口的不同,
map是双列集合,Collection是单列集合
Map的键是唯一,Collection的子系Set是唯一的
Map集合的数据结构只针对键有效
3.当集合中建重复时,对应的值取到的内容是最后一次添加进去的内容
2.Map集合的功能
1 //返回值被覆盖的内容 2 //第一次添加值时,集合中没有数据,被覆盖的内容为null,所以返回null 3 Map<String, Integer> map = new HashMap<>(); 4 map.put("a", 1); 5 map.put("a", 3); //此时输出,返回值是1 6 map.put("f", 4); 7 map.put("t", 2); 8 System.out.println(map);//输出结果为 {a=3, t=2, f=4} 9 map.size(); //长度 10 map.remove("a"); //删除指定键,与映射值 11 map.containsKey("a"); //是否包含键为"a"的的内容 12 map.containsValue(2); //是否包含值为2的内容 13 map.clear(); //清空 14 map.isEmpty(); //是否为空 15 16 }
3.Map的遍历
第一种
1 /* 2 * 1,首先获得到map中所有键, 3 * 2.在通过键获得对应的内容 4 */ 5 Map<String, Integer> map = new HashMap<>(); 6 map.put("a", 1); 7 map.put("a", 3); //此时输出,返回值是1 8 map.put("f", 4); 9 map.put("t", 2); 10 11 /* 12 * 先把键都添加到set集合中, 13 * 在使用set集合的迭代器, 14 * 通过get方法,在获取对应的值 15 */ 16 Set<String> set = map.keySet(); 17 Iterator<String> it = set.iterator(); 18 while(it.hasNext()) { 19 String s = it.next(); 20 Integer a = map.get(s); 21 System.out.println(a+ " "); 22 }
第二种遍历方式
1 HashMap<String, Integer> map = new HashMap<>(); 2 map.put("a", 1); 3 map.put("a", 3); // 此时输出,返回值是1 4 map.put("f", 4); 5 map.put("t", 2); 6 // 获取键值对对象 7 Set<Map.Entry<String, Integer>> set = map.entrySet(); 8 // 迭代器 9 Iterator<Map.Entry<String, Integer>> it = set.iterator(); 10 while (it.hasNext()) { 11 // 获取到每个键值对对象 12 Map.Entry<String, Integer> en = it.next(); 13 String s = en.getKey(); 14 Integer i = en.getValue(); 15 System.out.println(s + " " + i); 16 }
第三种
缺点不能删除
1 for (Map.Entry<String, Integer> entry : set) { 2 System.out.println(entry.getKey() + " " + entry.getValue()); 3 }
3.map遍历自定义对象
用增强for循环遍历
需要重写hashcode,和equals方法
4.linkedHashMap
保证怎么存怎么取的集合
5,treemap集合
排序去重复 treeset和treemap的功能是一样的
遍历自定义对象时,要记得Comparable