7

想象一下这些课程

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>>>

4

2 回答 2

7

groupingBy接受下游收集器,也可以是groupingBy

subjects.stream()
        .collect(groupingBy(
                Subject::getOrigin, 
                groupingBy(Subject::getType)    
        ));
于 2015-06-14T00:04:19.187 回答
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()))));
于 2015-06-14T00:16:22.237 回答