Map集合概述
Map<K,V> 将键映射到值的对象,一个映射不能包含重复的键;每个键最多只能映射到一个值
Map集合的特点:
1、Map集合是一个双列集合,一个元素包含两个值(一个key,一个Value)
2、Map集合中的元素,key和value的数据类型可以相同,也可以不同
3、Map集合中的元素,key是不允许重复的,无索引的,value是可以重复的
4、Map集合中的元素,key和value是一一对应的
5、Map集合后面的键对应的值会覆盖前面重复键的值
6、Map集合的键值对都可以为null
HashMap
java.util.HashMap<k,v>集合,implements Map<k,v>接口
HashMap集合的特点:
1、HashMap集合底层是哈希表:查询的速度特别的快
JDK1.8之前:数组+单向链表
JDK1.8之后:数组+单向链表/红黑树(链表的长度超过8):提高查询的速度
2、hashMap集合是一个无序的集合,存储元素和取出元素的顺序有可能不一致
LinkedHashMap
java.util.LinkedHashMap<k , v>集合extends HashMap<k , v>集合
LinkedHashMap的特点:
1.LinkedHashMap集合底层是哈希表+链表(保证迭代的顺序)
2.LinkedHashMap集合是一个有序的集合,存储元素和取出元素的顺序是一致的
TreeMap
元素按照键是排序,不重复,五索引,值不做要求。
Map集合的常用方法
public V put(K key,V value)
:把指定的键与指定的值添加到Map集合中
public V remove(Object key)
:把指定的键 所对应的键值对元素 在Map集合中删除,返回被删除元素的值
void clear()
:移除所有的键值对元素
public V get(Object key)
根据指定的键,在Map集合中获取对应的值
boolean containsKey(Object key)
判断集合中是否包含指定的键
boolean containsValue(Object value)
判断集合中是否包含指定的值
boolean isEmpty()
:判断集合是否为空
int size()
:集合的长度,也就是集合中键值对的个数
public class Demo01Map {
public static void main(String[] args) {
show();
show1();
show2();
show3();
}
//public V put(K key,V value):把指定的键与指定的值添加到Map集合中
//返回值:V
//存储键值对的时候,key不重复,返回值V是null
//存储键值对的时候,key重复,会使用新的value替换map中重复的value,返回被替换的value值
private static void show() {
//创建Map集合对象,多态
Map<String,String> map = new HashMap<>();
String v1 = map.put("李晨","范冰冰1");
System.out.println("V1:" + v1);//v1:null
String v2 = map.put("李晨","范冰冰2");
System.out.println("V2:" + v2);//V2:范冰冰1
System.out.println(map);//{李晨=范冰冰2}
map.put("杨过","小龙女");
map.put("郭靖","黄蓉");
map.put("冷峰","小龙女");
System.out.println(map);//{杨过=小龙女, 冷峰=小龙女, 李晨=范冰冰2, 郭靖=黄蓉}
}
//public V remove(Object key):把指定的键 所对应的键值对元素 在Map集合中删除,返回被删除元素的值
//返回值:V
//key存在,V返回被删除的值
//key不存在,V返回null
private static void show1() {
//创建Map集合对象,多态
Map<String,Integer> map = new HashMap<>();
map.put("赵丽颖",168);
map.put("刘辣子",165);
map.put("林志玲",177);
System.out.println(map);//{刘辣子=165, 林志玲=177, 赵丽颖=168}
//通过key删除键值对
Integer v1 = map.remove("林志玲");
System.out.println("V1:" + v1);//V1:177
System.out.println(map);//{刘辣子=165, 赵丽颖=168}
//删除不存在的
//如果把Integer写成int,会自动拆箱。但因为刘志哈不存在,所以会有NullPointException空指针异常
Integer v2 = map.remove("林志哈");
System.out.println("V2:" + v2);//V2:null
System.out.println(map);//{刘辣子=165, 赵丽颖=168}
}
//public V get(Object key)根据指定的键,在Map集合中获取对应的值
//返回值:V
//key存在,V返回对应的值
//key不存在,V返回null
private static void show2() {
//创建Map集合对象,多态
Map<String,Integer> map = new HashMap<>();
map.put("赵丽颖",168);
map.put("刘辣子",165);
map.put("林志玲",177);
Integer v1 = map.get("刘辣子");
System.out.println("v1" + v1);//165
Integer v2 = map.get("杨哈哈");
System.out.println("v2:" + v2);//v2:null
}
//boolean containsKey(Object key)判断集合中是否包含指定的键
//包含返回true,不包含返回false
private static void show3() {
//创建Map集合对象,多态
Map<String,Integer> map = new HashMap<>();
map.put("赵丽颖",168);
map.put("刘辣子",165);
map.put("林志玲",177);
boolean b1 = map.containsKey("刘辣子");
System.out.println("b1:" + b1);//b1:true
boolean b2 = map.containsKey("杨哈哈");
System.out.println("b2:" + b2);//b2:false
}
Map集合的第一种遍历方式:通过键找值的方式
Map集合中的方法:
Set<K> keySet()
返回此映射中包含的键的Set视图
实现步骤:
1、使用Map集合中的方法keySet(),把Map集合所有的key取出来,存储到一个Set集合中
2、遍历set集合,获取Map集合中的每一个key
3、遍历Map集合中的方法get(key),通过key找到value
public class Demo02KeySet {
public static void main(String[] args) {
//创建Map集合对象,多态
Map<String,Integer> map = new HashMap<>();
map.put("赵丽颖",168);
map.put("刘辣子",165);
map.put("林志玲",177);
//1、使用Map集合中的方法keySet(),把Map集合所有的key取出来,存储到一个Set集合中
Set<String> set = map.keySet();//key是String所以Set也是String
//2、遍历set集合,获取Map集合中的每一个key
Iterator<String> it = set.iterator();
while(it.hasNext()){
String key = it.next();
//3、遍历Map集合中的方法get(key),通过key找到value
Integer value = map.get(key);
System.out.println(key + "=" + value);
}
System.out.println("============");
//使用增强for遍历set集合
for (String key : set){
//3、遍历Map集合中的方法get(key),通过key找到value
Integer value = map.get(key);
System.out.println(key + "=" + value);
}
}
}
Map集合遍历的第二种方式:使用Entry对象遍历
Map集合中的方法:
Set<Map.Entry<K,V>> entrySet()
返回此映射中包含的映射关系的set视图
实现步骤:
1、使用Map集合中的方法entrySet(),把Map集合中多个Entry对象取出来,存储到一个Set集合中
2、遍历Set集合,获取每一个Entry对象
3、使用Entry对象中的方法getKey()和getValue()获取键与值
public class Demo03EntrySet {
public static void main(String[] args) {
//创建Map集合对象
Map<String,Integer> map = new HashMap<>();
map.put("赵丽颖",168);
map.put("刘辣子",165);
map.put("林志玲",177);
//1、使用Map集合中的方法entrySet(),把Map集合中多个Entry对象取出来,存储到一个Set集合中
Set<Map.Entry<String,Integer>> set = map.entrySet();
//2、遍历Set集合,获取每一个Entry对象
//使用迭代器遍历set集合
Iterator<Map.Entry<String,Integer>> it = set.iterator();
while (it.hasNext()){
Map.Entry<String,Integer> entry = it.next();
//3、使用Entry对象中的方法getKey()和getValue()获取键与值
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + "=" + value);
}
System.out.println("=============");
for(Map.Entry<String,Integer> entry:set){
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + "=" + value);
}
}
}
Map集合遍历的第三种方式:使用Lambda表达式遍历
Map<String , Integer> maps = new HashMap<>();
// 1.添加元素: 无序,不重复,无索引。
maps.put("娃娃",30);
maps.put("iphoneX",100);// Map集合后面重复的键对应的元素会覆盖前面重复的整个元素!
maps.put("huawei",1000);
maps.put("生活用品",10);
maps.put("手表",10);
System.out.println(maps);
// maps = {huawei=1000, 手表=10, 生活用品=10, iphoneX=100, 娃娃=30}
// maps.forEach(new BiConsumer<String, Integer>() {
// @Override
// public void accept(String key, Integer value) {
// System.out.println(key + "--->" + value);
// }
// });
maps.forEach((k, v) -> {
System.out.println(k + "--->" + v);
});
案例
需求:某班级有80名学生,现在选哟组成秋游活动,班长提供了四个景点依次是(A、B、C、D),每个学生只能选择一个景点,请统计出最终哪个景点想去的人数最多。
//1、把80个学生选择的数据拿进来
String[] selects = {"A","B","C","D"};
StringBuilder sb = new StringBuilder();
Random r = new Random();
for (int i = 0; i < 80; i++) {
sb.append(selects[r.nextInt(selects.length)]);
}
System.out.println("数组的长度为" + selects.length);//4
System.out.println("随机取到的数组下标为" + r.nextInt(selects.length));//2
System.out.println("按照随机下标取到的" + selects[r.nextInt(selects.length)]);//C
System.out.println("将取到的数据保存到sb中" + sb);
//2、定义一个Map集合记录最终统计结果,键是景点,值是选择的数量
Map<Character, Integer> ifos = new HashMap<>();
//3、遍历80个学生选择的数据
for (int i = 0; i < sb.length(); i++) {
//4、提取当前选择景点字符
char ch = sb.charAt(i);
//5、判断Map集合中是否存在这个键
if(ifos.containsKey(ch)) {
//让其值+1
ifos.put(ch,ifos.get(ch) + 1);
}else {
//说明此景点第一次被选中
ifos.put(ch,1);
}
}
System.out.println(ifos);//{A=19, B=22, C=23, D=16}
HashMap
HashMap存储自定义类型键值,特点是由键决定:、不重复、无索引
Map集合保证key是唯一的:
作为Key的元素,必须重写hashCode方法和equals方法,以保证key唯一
HashMap和HashSet底层原理是一样的,都是哈希表结构,只是HashMap的每个元素包含两个值而已。
public class Demo01HashMapSavePerson {
public static void main(String[] args) {
show01();
show02();
}
//HashMap存储自定义类型键值
//key:String类型:String类重写hashCode方法和equals方法,可以保证key唯一
//value:Person类型:value可以重复(同名同年龄的人视为同一个人)
private static void show01() {
//创建HashMap集合
HashMap<String,Person> map = new HashMap<>();
//往集合中添加元素
map.put("北京",new Person("张三",18));
map.put("上海",new Person("李四",19));
map.put("广州",new Person("王五",20));
map.put("北京",new Person("赵六",18));
//使用keySet和增强for遍历Map集合
Set<String> set = map.keySet();
for (String key:set){
Person value = map.get(key);
System.out.println(key + "-->" + value);
}
}
//HashMap存储自定义类型键值
//key:Person类型:Person类必须重写hashCode方法和equals方法,可以保证key唯一
//value:String类型,可以重复
private static void show02() {
//创建HashMap集合
HashMap<Person,String> map = new HashMap<>();
//往集合中添加元素
map.put(new Person("女王",18),"英国");
map.put(new Person("嬴政",19),"秦国");
map.put(new Person("普京",20),"毛毛");
map.put(new Person("女王",18),"辣子");
//使用entrySet和增强for遍历Map集合
Set<Map.Entry<Person,String>> set = map.entrySet();
for (Map.Entry<Person,String> entry : set){
Person key = entry.getKey();
String value = entry.getValue();
System.out.println(key + "-->" + value);
}
}
}
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
LinkedHashMap
LinkedHashMap有序、不重复、无索引。
这里的有序指的是保证存储和取出的元素顺序一致。
java.util.LinkedHashMap<K,V> entends HashMap<K,V>
Map 接口的哈希表和链表实现,具有可预知的迭代顺序
底层原理
哈希表+链表(记录元素的顺序),只是每个键值对元素又额外多了一个双链表的机制记录存储的顺序。
public class Demo01LinkedHashMap {
public static void main(String[] args) {
HashMap<String,String> map = new HashMap<>();
map.put("a","a");
map.put("c","c");
map.put("b","b");
map.put("a","d");
System.out.println(map);//{a=d, b=b, c=c}key不允许重复,无序
LinkedHashMap<String,String> linked = new LinkedHashMap<>();
linked.put("a","a");
linked.put("c","c");
linked.put("b","b");
linked.put("a","d");
System.out.println(linked);//key不允许重复,有序(存取顺序一致)
}
}
TreeMap
由键决定特性:不重复、无索引、可排序
可排序:按照键数据的大小默认升序(由小到大)排序,只能对键排序。
TreeMap集合是一定要排序的,可以默认排序,也可以将键按照指定的规则进行排序。
TreeMap跟TreeSet的底层原理也是一样的。
Hashtable
java.util.Hashtable<K,V>集合 implements Map<K,V>接口
Hashtable底层也是一个哈希表,是一个线程安全的集合,是但线程集合,速度慢
HashMap底层也是一个哈希表,是一个线程不安全的集合,是多线程的集合,速度快
HashMap集合:可以存储null值null键(之前学的所有集合都可为空)
Hashtable集合,不能存储null值null键
Hashtable和vector集合一样,在jdk1.2版本之后被更先进的集合(HashMap,ArrayList)取代了
Hashtable的子类Properties依然活跃在历史舞台
Properties集合是一个唯一和IO流相结合的集合
public class Demo02Hashtable {
public static void main(String[] args) {
HashMap<String,String> map = new HashMap<>();
map.put(null,"a");
map.put("b",null);
map.put(null,null);
System.out.println(map);//{null=null, b=null},null也存在键值重复的问题
Hashtable<String,String> table = new Hashtable<>();
table.put(null,"a");//NullPointerException
table.put("b",null);//NullPointerException
table.put(null,null);//NullPointerException
}
}