如何使用Java 8 Collectors grouping来获取带有集合地图的Map?

时间:2015-06-13 23:05:49

标签: java-8 java-stream collectors

想象一下这些类

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

2 个答案:

答案 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()))));