Java:List转Map (用stream实现)
//实体类
public class Student {
private String no; //学号
private String name; //姓名
//构造方法忽略
//set、get 方法忽略
}
public class Teacher{
private String no; //教师号
private String name; //姓名
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
一、List<Object>
转 Map<String, String>
//声明一个List集合
List<Student> list = new ArrayList();
list.add(new Student("1001", "小A"));
list.add(new Student("1001", "小B"));//学号重复(下面特殊处理)
list.add(new Student("1002", "小C"));
list.add(new Student("1003", "小D"));
//将list转map (map的键重复不会报错,下面已经处理)
Map<String, String> map =
list.stream().collect(Collectors.toMap(
Student::getNo,
Student::getName,
(key1 , key2) -> key2
));
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
二、List<Object>
转 Map<String, Object>
(返回对象本身)
//声明一个List集合
List<Student> list = new ArrayList();
list.add(new Student("1001", "小A"));
list.add(new Student("1001", "小B"));
list.add(new Student("1002", "小C"));
list.add(new Student("1003", "小D"));
//将list转map (map的键去重)
Map<String, Student> map =
list.stream().collect(Collectors.toMap(
Student::getNo,
stu -> stu,
(key1 , key2) -> key2
));
或者
//将list转map (map的键去重)
Map<String, Student> map =
list.stream().collect(Collectors.toMap(
Student::getNo,
Function.identity(),
(key1 , key2) -> key2
));
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
三、List<Object2>
转 Map<String, Object1>
(返回另一个对象)
//声明一个List集合
List<Student> list = new ArrayList();
list.add(new Student("1001", "小A"));
list.add(new Student("1001", "小B"));
list.add(new Student("1002", "小C"));
list.add(new Student("1003", "小D"));
//将list转map (map的键去重)
Map<String, Teacher> map =
list.stream().collect(Collectors.toMap(
Student::getNo,
stu -> {
Teacher teacher = new Teacher();
teacher.setNo(stu.getNo());
teacher.setName(stu.getName());
return teacher;
},
(key1 , key2) -> key2
));
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
四、List<Object>
转 Map<String, List<Object>>
(分组)
//声明一个List集合
List<Student> list = new ArrayList();
list.add(new Student("1001", "小A"));
list.add(new Student("1001", "小B"));
list.add(new Student("1002", "小C"));
list.add(new Student("1003", "小D"));
//将list转map (以某个属性来分组,将分组后相同的map放在一起)
Map<String, List<Student>> map =
list.stream().collect( Collectors.groupingBy(Student::getNo) );
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
五、学习链接:
https://blog.csdn.net/qq_39629277/article/details/83012548
https://blog.csdn.net/lu930124