Java 17 Lambda + Stream中的filter / map / sorted / flatMap / collect,熟悉Java的record类型
·
record Employee(String name,int salary){}
record EmployeeTwo(String name,String dept,int salary){}
public static void main(String[] args) {
List<Employee> list = List.of(new Employee("1",12000),new Employee("2",14000),
new Employee("3",9000),new Employee("4",2000));
// 1过滤+映射
List<String> nameList = list.stream().filter(e -> e.salary>10000).map(e -> e.name).toList();
// System.out.println(nameList);
//[1, 2]
// 2排序+收集
List<Employee> top2 = list.stream().sorted((a,b)->b.salary()-a.salary())
.limit(4).toList();
// System.out.println(top2.stream().map(e -> e.name).toList());
//[2, 1, 3, 4]
// 3分组+统计
List<EmployeeTwo> listTwo = List.of(new EmployeeTwo("1","技术",112000),new EmployeeTwo("2","销售",12000),
new EmployeeTwo("3","技术",12000),new EmployeeTwo("4","销售",3000),
new EmployeeTwo("5","销售",9000));
Map<String, IntSummaryStatistics> result = listTwo.stream().collect(
Collectors.groupingBy(EmployeeTwo::dept, Collectors.summarizingInt(EmployeeTwo::salary)));
// result.forEach((dept,stats) -> System.out.println(dept+":人数="+stats.getCount()+"平均="+stats.getAverage()));
//技术:人数=2平均=62000.0
//销售:人数=3平均=8000.0
// 4去重
record Student(String name,List<String> hobbies){}
List<Student> students = List.of(new Student("1号",List.of("篮球","编程","音乐")),
new Student("2号",List.of("编程","画画","篮球")),
new Student("3号",List.of("音乐","游泳")));
List<String> allHobbies = students.stream().flatMap(s -> s.hobbies().stream())
.distinct().sorted().toList();
// System.out.println(allHobbies);
//[游泳, 画画, 篮球, 编程, 音乐]
// SpringApplication.run(ExerciseStreamApplication.class, args);
}
更多推荐


所有评论(0)