目录
- 1.Map
- 1.1 常用成员方法
- 1.2 遍历 Map
- 2.HashMap
- 3.TreeMap
- 4.可变参数
- 5.创建不可变集合
1.Map
Interface Map<K, V>
:
- K:键的数据类型
- V:值的数据类型
- 键不能重复,值可以重复。
- 键和值是一一对应的,每一个键只能找到自己对应的值。
- (键+值) 这个整体我们称之为“键值对”或者“键值对对象”,在 Java 中叫做 “Entry对象”。
package com.qdu.mapdemo1;
import java.util.HashMap;
import java.util.Map;
public class MyMap1 {
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
map.put("2022001","小智");
map.put("2022002","小美");
map.put("2022003","大胖");
System.out.println(map);
// {2022001=小智, 2022002=小美, 2022003=大胖}
}
}
1.1 常用成员方法
package com.qdu.mapdemo1;
import java.util.HashMap;
import java.util.Map;
public class MyMap2 {
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
// V put(K key, V value) 添加元素
// 如果要添加的键不存在,那么会把键值对都添加到集合中
map.put("2021201380","小智");
map.put("2021201381","小美");
map.put("2021201382","大胖");
map.put("2021201383","小黑");
map.put("2021201384","大师");
System.out.println(map); // {2021201381=小美, 2021201382=大胖, 2021201380=小智, 2021201383=小黑, 2021201384=大师}
// 如果要添加的键是存在的,那么会覆盖原先的值,把原先值当做返回值进行返回
String s = map.put("2021201380", "aaa");
System.out.println(s); // 小智
System.out.println(map); // {2021201381=小美, 2021201382=大胖, 2021201380=aaa, 2021201383=小黑, 2021201384=大师}
// V remove(Object key) 根据键删除键值对元素
s = map.remove("2021201380");
System.out.println(s); // aaa
System.out.println(map); // {2021201381=小美, 2021201382=大胖, 2021201383=小黑, 2021201384=大师}
// boolean containsKey(Object key) 判断集合是否包含指定的键
boolean result1 = map.containsKey("2021201380");
boolean result2 = map.containsKey("2021201381");
System.out.println(result1); // false
System.out.println(result2); // true
// boolean containsValue(Object value) 判断集合是否包含指定的值
result1 = map.containsValue("小智");
result2 = map.containsValue("小美");
System.out.println(result1); // false
System.out.println(result2); // true
// int size() 集合的长度,也就是集合中键值对的个数
int size = map.size();
System.out.println(size); // 4
// boolean isEmpty() 判断集合是否为空
boolean empty1 = map.isEmpty();
System.out.println(empty1); // false
// void clear() 移除所有的键值对元素
map.clear();
System.out.println(map); // {}
boolean empty2 = map.isEmpty();
System.out.println(empty2); // true
}
}
1.2 遍历 Map
package com.qdu.mapdemo1;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MyMap3 {
public static void main(String[] args) {
// 创建集合并添加元素
Map<String,String> map = new HashMap<>();
map.put("1号丈夫","1号妻子");
map.put("2号丈夫","2号妻子");
map.put("3号丈夫","3号妻子");
map.put("4号丈夫","4号妻子");
map.put("5号丈夫","5号妻子");
// 获取到所有的键
Set<String> keys = map.keySet();
// 遍历Set集合得到每一个键
for (String key : keys) {
// 通过每一个键key,来获取到对应的值
String value = map.get(key);
System.out.println(key + "---" + value);
}
}
}
package com.qdu.mapdemo1;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MyMap4 {
public static void main(String[] args) {
// 创建集合并添加元素
Map<String,String> map = new HashMap<>();
map.put("1号丈夫","1号妻子");
map.put("2号丈夫","2号妻子");
map.put("3号丈夫","3号妻子");
map.put("4号丈夫","4号妻子");
map.put("5号丈夫","5号妻子");
// 获取所有的键值对对象
// Set集合中装的是键值对对象(Entry对象),而Entry里面装的是键和值
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : entries) {
// 得到每一个键值对对象
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + "---" + value);
}
}
}
2.HashMap
HashMap 的特点:
- HashMap 是 Map 里面的一个实现类。
- 没有额外需要学习的特有方法,直接使用 Map 里面的方法就可以了。
- HashMap 跟 HashSet 一样,底层都是哈希表。
- 依赖 hashCode 方法和 equals 方法保证键的唯一。
- 如果键要存储的是自定义对象,需要重写 hashCode 和 equals 方法。
示例:创建一个 HashMap 集合,键是学生对象(Student),值是籍贯(String)。存储三个键值对元素并遍历。
package com.qdu.mapdemo1;
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = 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;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
package com.qdu.mapdemo1;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MyMap5 {
public static void main(String[] args) {
HashMap<Student,String> hm = new HashMap<>();
Student s1 = new Student("xiaohei",23);
Student s2 = new Student("dapang",22);
Student s3 = new Student("xiaomei",22);
hm.put(s1,"江苏");
hm.put(s2,"北京");
hm.put(s3,"天津");
// 第一种:先获取到所有的键,再通过每一个键来找对应的值
Set<Student> keys = hm.keySet();
for (Student key : keys) {
String value = hm.get(key);
System.out.println(key + "----" + value);
}
System.out.println("----------------------------------------");
// 第二种:先获取到所有的键值对对象,再获取到里面的每一个键和每一个值
Set<Map.Entry<Student, String>> entries = hm.entrySet();
for (Map.Entry<Student, String> entry : entries) {
Student key = entry.getKey();
String value = entry.getValue();
System.out.println(key + "----" + value);
}
System.out.println("----------------------------------------");
// 第三种:
hm.forEach(
(Student key, String value)->{
System.out.println(key + "----" + value);
}
);
}
}
3.TreeMap
TreeMap 的特点:
- TreeMap 是 Map 里面的一个实现类。
- 没有额外需要学习的特有方法,直接使用 Map 里面的方法就可以了。
- TreeMap 跟 TreeSet 一样,底层都是红黑树。
- 依赖自然排序或者比较器排序,对键进行排序。
- 如果键存储的是自定义对象,需要实现 Comparable 接口或者在创建 TreeMap 对象时给出比较器排序规则。
示例:创建一个 TreeMap 集合,键是学生对象(Student),值是籍贯(String)。学生属性姓名和年龄,按照年龄进行排序并遍历。
(1) 自然排序
package com.qdu.maptest;
public 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;
}
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Student o) { // 从大到小排序
// 主要条件,按照年龄进行排序
int result = o.getAge() - this.getAge();
// 次要条件,按照姓名排序
result = result == 0 ? o.getName().compareTo(this.getName()) : result;
return result;
}
}
package com.qdu.maptest;
import java.util.Comparator;
import java.util.TreeMap;
public class Test1 {
public static void main(String[] args) {
TreeMap<Student,String> tm = new TreeMap<>();
Student s1 = new Student("xiaohei",23);
Student s2 = new Student("dapang",22);
Student s3 = new Student("xiaomei",22);
tm.put(s1,"江苏");
tm.put(s2,"北京");
tm.put(s3,"天津");
tm.forEach(
(Student key, String value)->{
System.out.println(key + "---" + value);
}
);
}
}
(2) 比较器排序
package com.qdu.maptest;
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = 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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
package com.qdu.maptest;
import java.util.Comparator;
import java.util.TreeMap;
public class Test1 {
public static void main(String[] args) {
TreeMap<Student,String> tm = new TreeMap<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int result = o1.getAge() - o2.getAge();
result = result == 0 ? o1.getName().compareTo(o2.getName()) : result;
return result;
}
});
Student s1 = new Student("xiaohei",23);
Student s2 = new Student("dapang",22);
Student s3 = new Student("xiaomei",22);
tm.put(s1,"江苏");
tm.put(s2,"北京");
tm.put(s3,"天津");
tm.forEach(
(Student key, String value)->{
System.out.println(key + "---" + value);
}
);
}
}
4.可变参数
可变参数:就是形参的个数是可以变化的。
格式:修饰符 返回值类型 方法名(数据类型...变量名) { }
注意事项:
- 这里的变量其实是一个数组。
- 如果一个方法有多个参数,包含可变参数,可变参数要放在最后。
package com.qdu.variableparameter;
public class MyVariableParameter3 {
public static void main(String[] args) {
int sum1 = getSum(21, 52, 39, 81, 15);
System.out.println(sum1); // 208
}
public static int getSum(int... arr) {
System.out.println(arr); // [I@776ec8df
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
return sum;
}
}
5.创建不可变集合
在 List、Set、Map 接口中,都存在 of 方法,可以创建一个不可变的集合。
这个集合不能添加,不能删除,不能修改。
但是可以结合集合的带参构造,实现集合的批量添加。
package com.qdu.variableparameter;
import java.util.*;
public class MyVariableParameter4 {
public static void main(String[] args) {
// static <E> List<E> of(E...elements) 创建一个具有指定元素的List集合对象
List<String> list = List.of("a", "b", "c", "d");
System.out.println(list); // [a, b, c, d]
// 不能添加,不能删除,不能修改
// list.add("Q");
// list.remove("a");
// list.set(0,"A");
// System.out.println(list);
// 实现集合的批量添加
ArrayList<String> list3 = new ArrayList<>(List.of("a", "b", "c", "d"));
System.out.println(list3); // [a, b, c, d]
}
}
package com.qdu.variableparameter;
import java.util.*;
public class MyVariableParameter4 {
public static void main(String[] args) {
// static <E> Set<E> of(E...elements) 创建一个具有指定元素的Set集合对象
// 传递的参数中不能存在重复的元素
Set<String> set = Set.of("a", "b", "c", "d");
System.out.println(set);
}
}
package com.qdu.variableparameter;
import java.util.*;
public class MyVariableParameter4 {
public static void main(String[] args) {
// static <K,V> Map<K,V> of(E...elements) 创建一个具有指定元素的Map集合对象
Map<String, String> map = Map.of("zhangsan", "江苏", "lisi", "北京", "wangwu", "天津");
System.out.println(map);
}
}
在 Map 接口中,还有一个 ofEntries 方法可以提高代码的阅读性。
首先把键值对封装成一个 Entry 对象,再把这个 Entry 对象添加到集合当中。
package com.qdu.variableparameter;
import java.util.*;
public class MyVariableParameter4 {
public static void main(String[] args) {
Map<String, String> map = Map.ofEntries(
Map.entry("zhangsan", "江苏"),
Map.entry("lisi", "北京"));
System.out.println(map);
}
}