想象一下这些类
class Subject {
private int id;
private Type type;
private String origin;
private String name;
Subject(int id, Type type, String origin, String name) {
this.id = id;
this.type = type;
this.origin = origin;
this.name = name;
}
// Getters and Setters
}
enum Type {
TYPE1,
TYPE2
}
我有一个主题类列表
List<Subject> subjects = Arrays.asList(
new Subject(1, Type.TYPE1, "South", "Oscar"),
new Subject(2, Type.TYPE2, "South", "Robert"),
new Subject(3, Type.TYPE2, "North", "Dan"),
new Subject(4, Type.TYPE2, "South", "Gary"));
我希望首先使用Collectors.groupingBy()
地图分组Subject
对象Subject.origin
,然后按Subject.type
分组
获得像这样的对象Map<String, Map<Type, List<Subject>>>
答案 0 :(得分:7)
groupingBy
接受下游收集器,也可以是groupingBy
:
subjects.stream()
.collect(groupingBy(
Subject::getOrigin,
groupingBy(Subject::getType)
));
答案 1 :(得分:4)
Stream<Subject> subjects = Stream.of(
new Subject(1, Subject.Type.TYPE1, "South", "Oscar"),
new Subject(2, Subject.Type.TYPE2, "South", "Robert"),
new Subject(3, Subject.Type.TYPE2, "North", "Dan"),
new Subject(4, Subject.Type.TYPE2, "South", "Gary"));
Map<String, Map<Subject.Type, List<Subject>>> subjectByOriginByType;
subjectByOriginByType = subjects.collect(Collectors.groupingBy(
s->s.getOrigin(), Collectors.groupingBy(
s->s.getType(),
Collectors.mapping((Subject s) -> s, Collectors.toList()))));