JavaDay11-Map、HashMap、LinkedHashMap、TreeMap、Collections工具类
一、双列集合的特点
1、一次存储一对键值对
2、键不能重复,值可以重复
3、键值对一一对应
4、键+值--“键值对”、“简直对对象”、在Java中叫做“Entry对象”
二、双列集合的体系结构
Map--HashMap、TreeMap--LinkedHashMap
三、双列集合的常用API
1、public V put(K key, V value)--添加元素
细节:添加/覆盖
- 键不存在,直接添加,返回值为null
- 键已存在,覆盖原来的value,并且返回原来的value
2、public V remove(Object key)--删除元素 - 删除整个键值对,返回被删除的值
3、public void clear()--清空集合
4、public boolean containsKey(Object key)--判断是否有键
5、public boolean containsValue(Object value)--判断是否有值
6、public boolean isEmpty()--判断集合是否为空
7、public int size()--返回集合长度
import java.util.HashMap;
import java.util.Map;
//Map的常用API
public class MapDemo01 {
public static void main(String[] args) {
Map<String, String> mp = new HashMap<>();
//mp
String v=mp.put("郭靖","黄蓉");//v=null
String v2=mp.put("郭靖","黄蓉蓉");//v1=黄蓉
mp.put("孙俪","邓超");
mp.put("sb","dcm");
//System.out.println(mp);
//remove
//mp.remove("孙俪");
//System.out.println(mp);
//clear
//mp.clear();
//System.out.println(mp);
//containsKey
boolean key = mp.containsKey("郭靖");
//System.out.println(key);
//containsValue
boolean value = mp.containsValue("黄蓉");
//System.out.println(value);
//isEmpty
boolean empty = mp.isEmpty();
//System.out.println(empty);
//size
int size = mp.size();
System.out.println(size);
}
}
四、Map的遍历方式:
1、获取所有的键,放到一个单列集合中,遍历单列集合(keySet、map.get(key))
2、键值对(getKey、getValue)
3、Lambda表达式
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
//Map遍历的第一种方式
public class MapDemo02 {
public static void main(String[] args) {
Map<String,String> map=new HashMap<>();
map.put("蜡笔小新","白龙马");
map.put("妮妮","秦始皇");
map.put("王大陆","貂蝉");
//keySet()方法--获取map中所有的key并存入set集合中
Set<String> key = map.keySet();
/* for (String s : key) {
String s1 = map.get(s);//map.get(key)方法--根据key获取map中对应的value
System.out.println(s+"="+s1);
}*/
/* Iterator<String> it = key.iterator();
while (it.hasNext()){
String key1 = it.next();
String value = map.get(key1);
System.out.println(key1+"="+value);
}*/
key.forEach((s)-> {
String value = map.get(s);
System.out.println(s+"="+value);
});
}
}
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
//Map集合的第二种遍历方式
public class MapDemo03 {
public static void main(String[] args) {
Map<String,String> map=new HashMap<>();
map.put("甄嬛","灵隐寺");
map.put("唐僧","西天取经");
map.put("白龙马","胧月");
//entrySet()方法--把键值对entry对象存放到Set集合中
Set<Map.Entry<String, String>> entries = map.entrySet();
/* for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();//entry.getKey()获取entry对象的键
String value = entry.getValue();//entry.getKey()获取entry对象的值
System.out.println(key+"="+value);
}*/
/*Iterator<Map.Entry<String, String>> it = entries.iterator();
while (it.hasNext()){
Map.Entry<String, String> entry = it.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+"="+value);
}*/
entries.forEach((entry)-> {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+"="+value);
});
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
//Map的第三种遍历方式-Lambda表达式
public class MapDemo04 {
public static void main(String[] args) {
Map<String,String> map=new HashMap<>();
map.put("周杰伦","七里香");
map.put("周杰","尔康");
map.put("紫薇","冬儿");
/* map.forEach(new BiConsumer<String, String>() {
@Override
public void accept(String key, String value) {
System.out.println(key+"="+value);
}
});*/
map.forEach((key, value)->System.out.println(key+"="+value));//Lambda表达式
}
}
五、HashMap
1、是Map的实现类,继承Map的所有方法
2、键--无序(存取顺序不一致)、不重复、无索引
3、底层是哈希表结构
4、键依赖hashCode和equals方法保证不重复
5、如果键存的是自定义对象,需要重写hashCode和equals方法;值存储自定义对象时不需要重写
import java.util.*;
import java.util.function.BiConsumer;
public class HashMapDemo01 {
/*
需求:创建一个HashMap集合,键是学生对象,值是籍贯
存储三个键值对元素,并遍历
要求:同姓名同年龄认为是一个学生
*/
//student类需要重写hashCode和equals方法
public static void main(String[] args) {
HashMap<Student,String> hashMap = new HashMap<>();
Student stu1 = new Student("李飞刀", 23);
Student stu2 = new Student("李飞抢", 21);
Student stu3 = new Student("李飞杨", 88);
Student stu4 = new Student("李飞杨", 88);
hashMap.put(stu1,"广东");
hashMap.put(stu2,"山东");
hashMap.put(stu3,"河东");
hashMap.put(stu4,"西东");
/* for (Student stus : hashMap.keySet()) {
String birs = hashMap.get(stus);
System.out.println("学生:"+stus+"\n籍贯:"+birs);
}*/
/* Set<Map.Entry<Student, String>> entries = hashMap.entrySet();
Iterator<Map.Entry<Student, String>> it = entries.iterator();
while (it.hasNext()){
Map.Entry<Student, String> entry = it.next();
Student key = entry.getKey();
String value = entry.getValue();
System.out.println("学生:"+key+"\n籍贯:"+value);
}*/
hashMap.forEach((student, bir)-> System.out.println("学生:"+student+"\n籍贯:"+bir));
}
}
class Student implements Comparable<Student>{
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取
* @return age
*/
public int getAge() {
return age;
}
/**
* 设置
* @param age
*/
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Student{name = " + name + ", age = " + age+ "}";
}
//重写hashCode和equals方法
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public int compareTo(Student o) {
if(this.getAge()==o.getAge()){
return this.getName().compareTo(o.getName());
}
return this.getAge()-o.getAge();
}
}
import java.util.*;
public class HashMapDemo02 {
/*
某班有80个学生,现在要组织春游活动,班长提供了四个景点(A B C D)
每人只能选一个景点,统计哪个景点想去的人最多
*/
public static void main(String[] args) {
//random模拟随机投票结果
ArrayList<String> vote = new ArrayList<>();
String[] arr={"A","B","C","D"};//四个景点
Random r = new Random();
for (int i = 0; i < 80; i++) {
int index = r.nextInt(arr.length);
vote.add(arr[index]);
}
//System.out.println(vote);
//HashMap统计投票结果
HashMap<String, Integer> mapVote = new HashMap<>();
Iterator<String> itVote = vote.iterator();
while (itVote.hasNext()){
String name = itVote.next();
if (mapVote.containsKey(name)){
int count = mapVote.get(name);//获取投票次数
count++;
mapVote.put(name,count);//新的投票次数存入hashMap
}else {
mapVote.put(name,1);//name景点第一次投票
}
}
//遍历HashMap
System.out.println("投票结果为:\n"+mapVote);
//统计哪个景点想去的人最多
int max=0;
String key = null;
for (Map.Entry<String, Integer> entry : mapVote.entrySet()) {
Integer value = entry.getValue();
if (value>max) {
max=value;
key = entry.getKey();
}
}
System.out.println("同学们最想去的景点是:\n"+key+",有"+max+"人想去。");
}
}
六、LinkedHashMap
1、有序、不重复、无索引
2、双向链表+哈希表
七、TreeMap
1、底层原理:红黑树
2、键--不重复、无索引、可排序
3、排序--对键进行排序
4、排序规则:
- 实现comparable接口
- 创建集合时传递Comparator对象
import java.util.Comparator;
import java.util.TreeMap;
//TreeMap排序练习
public class TreeMapDemo01 {
public static void main(String[] args) {
//按照整数从大到小排序
TreeMap<Integer, String> treeMap = new TreeMap<>((o1,o2)-> {return (o2-o1);});//return o2-o1;
treeMap.put(1234,"hfkd");
treeMap.put(234,"hfkd");
treeMap.put(34,"hfkd");
System.out.println(treeMap);
//按照年龄进行排序,如果年龄相同按照姓名字母排序,否则视为同一人,舍弃
Student stu1 = new Student("zhangsan",12);
Student stu2 = new Student("hangsan",12);
Student stu3 = new Student("zhangsang",52);
Student stu4 = new Student("hangsa",88);
TreeMap<Student, String> treeMapStu = new TreeMap<>();
treeMapStu.put(stu1,"广东");
treeMapStu.put(stu2,"山东");
treeMapStu.put(stu3,"合肥");
treeMapStu.put(stu4,"新疆");
System.out.println(treeMapStu);
}
}
import java.util.TreeMap;
import java.util.function.BiConsumer;
/*
TreeMap练习:
需求:字符串aababcabcdabcde
统计字符串中每一个字符出现的次数
按照以下格式输出:a(5)b(4)c(3)d(2)e(1)
*/
public class TreeMapDemo02 {
public static void main(String[] args) {
TreeMap<Character,Integer> treeMap = new TreeMap<>();
String str="aababcabcdabcde";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);//遍历字符串str
if (treeMap.containsKey(c)){
int count=treeMap.get(c);
count++;
treeMap.put(c,count);
}else {
treeMap.put(c,1);
}
}
//按照需求格式遍历并且打印
treeMap.forEach((key,val)->System.out.print(key+"("+val+")"));
}
}
八、Collections
1、工具类,直接 类名.方法 来调用方法
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
//Collections工具类
public class CollectionsDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
//批量添加元素
Collections.addAll(list,"gsjfdgs","hdkfhk","hgdsjf");
System.out.println(list);
//打乱集合元素
Collections.shuffle(list);
System.out.println(list);
//排序
Collections.sort(list);
System.out.println(list);
}
}

浙公网安备 33010602011771号