[英]Java-Stream - How Collecor groupingBy() to split a Map into multiple Submaps
[英]Java-Stream - How to apply sorting while using Collector groupingBy
我正在使用Collectors.groupingBy
將可能的對象分組到列表中。 舉例如下:
public class Test {
public static void main(String[] args) {
Student student1 = new Student(98,"man","CHEN",20);
Student student2 = new Student(100,"man","PETER",20);
Student student3 = new Student(100,"man","TMAC",21);
ArrayList<Student> list = Lists.newArrayList(student1, student2, student3);
Map<Integer, List<StudentDTO>> map = list.stream()
.collect(Collectors.groupingBy(Student::getAge,
Collectors.mapping(e -> new StudentDTO(e.getScore(), e.getName()),
Collectors.toList())
));
System.out.println(map);
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class Student {
private Integer score;
private String sex;
private String name;
private Integer age;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class StudentDTO {
private Integer score;
private String name;
}
}
Output:
{20=[Test.StudentDTO(score=98, name=CHEN),
Test.StudentDTO(score=100, name=PETER)],
21=[Test.StudentDTO(score=100, name=TMAC)]}
但我的目標是使用Comparator.comparing
與流按score
對StudentDTO
進行排序。 我怎樣才能做到這一點?
所需的 output:
{20=[Test.StudentDTO(score=100, name=PETER),
Test.StudentDTO(score=98, name=CHEN)],
21=[Test.StudentDTO(score=100, name=TMAC)]}
要按score
降序對StudentDTO
的每個列表進行排序,您可以使用以下比較器:
Comparator.comparingInt(StudentDTO::getScore).reversed()
並且要在收集結果時應用排序,您可以使用收集器collectingAndThen()
作為groupingBy()
的下游
List<Student> students = List.of(student1, student2, student3);
Map<Integer, List<StudentDTO>> map = students.stream()
.collect(Collectors.groupingBy(
Student::getAge,
Collectors.collectingAndThen(
Collectors.mapping(e -> new StudentDTO(e.getScore(), e.getName()),
Collectors.toList()),
list -> { list.sort(Comparator.comparingInt(StudentDTO::getScore).reversed()); return list; }
)
));
注意:針對具體實現編寫代碼會使其變得不靈活,您可能想了解使用抽象的好處。 請參閱“編程到接口”是什么意思?
嘗試這個。 (我添加了import static java.util.stream.Collectors.*;
)
Map<Integer, List<StudentDTO>> map = list.stream()
.collect(groupingBy(Student::getAge,
mapping(e -> new StudentDTO(e.getScore(), e.getName()),
collectingAndThen(toList(),
x -> x.stream()
.sorted(Comparator.comparing(StudentDTO::getScore).reversed())
.collect(toList())))));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.