文章目录
- 一、stream toMap、groupingBy、mapping的综合应用
-
一、stream toMap、groupingBy、mapping的综合应用
1、前提准备
①、实体类
package com.cfay.demo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class Student implements Serializable {
private Integer id;
private String name;
private Integer age;
}
②、数据准备
package com.cfay.demo;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class StudentData {
private StudentData() {
}
public static List<Student> buildStudents() {
List<Student> students = new ArrayList<>();
students.add(new Student(1, "小扇", 20));
students.add(new Student(1, "小雨", 22));
students.add(new Student(1, "小钰", 19));
students.add(new Student(1, null, 19));
students.add(new Student(2, "小蓝", 21));
students.add(new Student(2, "小天", 20));
return students.stream().filter(student ->
Objects.nonNull(student.getName())).sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
}
}
2、核心代码:
package com.cfay.demo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
handleStudentIdNameSplicteMap();
System.out.println("===================================");
handleStudentIdNamesMap();
}
private static void handleStudentIdNameSplicteMap() {
System.out.println("toMap ......");
Map<Integer, String> studentIdNameMap1 = StudentData.buildStudents().stream().collect(Collectors.toMap(Student::getId,
Student::getName, (pre, act) -> pre + "," + act));
System.out.println(studentIdNameMap1);
System.out.println("groupingBy ......");
Map<Integer, String> studentIdNameMap2 = StudentData.buildStudents().stream().collect(Collectors.groupingBy(Student::getId,
Collectors.mapping(Student::getName, Collectors.joining(","))));
System.out.println(studentIdNameMap2);
}
private static void handleStudentIdNamesMap() {
System.out.println("toMap ......");
Map<Integer, List<String>> studentIdNamesMap1 = StudentData.buildStudents().stream().collect(Collectors.toMap(Student::getId, student ->
new ArrayList<>(Collections.singletonList(student.getName())), (pre, act) -> {
pre.addAll(act);
return pre;
}));
System.out.println(studentIdNamesMap1);
System.out.println("groupingBy ......");
Map<Integer, List<String>> studentIdNamesMap2 = StudentData.buildStudents().stream().collect(Collectors.groupingBy(Student::getId,
Collectors.mapping(Student::getName, Collectors.toList())));
System.out.println(studentIdNamesMap2);
}
}
3、运行结果
![Java8 stream toMap、groupingBy、mapping的综合应用_第1张图片](http://img.e-com-net.com/image/info8/89d31efecef34d318bf3ffbe0fccd956.jpg)