1.列表转Map
常用方法
public static void main(String[] args) {
Student student1 = new Student(1, "a", 10);
Student student2 =new Student(3,"a",10);
Student student3 =new Student(3,"a",10);
ArrayList<Student> students = new ArrayList<>();
students.add(student1);
students.add(student2);
students.add(student3);
Map<Integer, Student> map = students.stream().collect(Collectors.toMap(Student::getId, Function.identity()));
System.out.println(map);
}
**缺点:**当存在多个key的时候会报错
Duplicate key Student{id=3, name='a', age=10}
**解决方法:**利用toMap的第三个参数来确定在冲突key的时候要保存哪一个
public static void main(String[] args) {
Student student1 = new Student(1, "a", 10);
Student student2 =new Student(3,"a",11);
Student student3 =new Student(3,"a",10);
ArrayList<Student> students = new ArrayList<>();
students.add(student1);
students.add(student2);
students.add(student3);
// 使用第一个
Map<Integer, Student> map = students.stream().collect(Collectors.toMap(Student::getId, Function.identity(),(first, second) ->first));
System.out.println(map);
}
注意:
当list为为空时,可以转map,当list为null时,转map时候会出现空指针异常
ArrayList<Student> students = new ArrayList<>();
Map<Integer, Student> map = students.stream().collect(Collectors.toMap(Student::getId, Function.identity(),(first, second) ->first));
->sout
{}
ArrayList<Student> nullStudents=null;
Map<Integer, Student> testMap = nullStudents.stream().collect(Collectors.toMap(Student::getId, Function.identity(),(first, second) ->first));
- >sout
Exception in thread "main" java.lang.NullPointerException
待更新