代码之家  ›  专栏  ›  技术社区  ›  Eduardo

Java:分组,然后映射

  •  6
  • Eduardo  · 技术社区  · 7 年前

    我有一股 Event s

    public class Event {
        Location location;
        double turnout;
        //... other fields & getters
    }
    

    还有统计学课 EventStatistics

    public class EventStatistics {
        // Stats properties e.g. turnout standard deviation/median
    
        public EventStatistics(List<Event> events) {
            // Generate stats
        }
    }
    

    我需要按位置对所有活动进行分组&创建位置和事件统计信息的地图 Map<Location, EventStatistics>

    分组依据是:

    Map<Location, List<Event>> byLocation = events.stream().collect(groupingBy(Event::getLocation));
    

    我知道这里超载了 groupingBy(function, collector) 收集器。我可以用这个来生成我的 映射(<);位置、事件统计信息> 在一条流中?

    3 回复  |  直到 7 年前
        1
  •  13
  •   JB Nizet    7 年前

    你只需要 collectingAndThen :

    Map<Location, EventStatistics> result = 
        events.stream()
              .collect(Collectors.groupingBy(Event::getLocation,
                                             Collectors.collectingAndThen(
                                                 Collectors.toList(), 
                                                 EventStatistics::new)));
    
        2
  •  2
  •   Andreas dfa    7 年前

    您可以构建自己的 Collector 使用 Collector.of(...) ,如下所示:

    Map<Location, EventStatistics> collect = events.stream().collect(groupingBy(Event::getLocation,
            Collector.of(ArrayList::new,
                         List::add,
                         (left, right) -> { left.addAll(right); return left; },
                         EventStatistics::new)
    ));
    
        3
  •  1
  •   daniu    7 年前

    如果您的 EventStatistics 我们可以接受单身 Events 而不是完整列表,以及合并两个统计信息的方法,如

    EventStatistics {
        public EventStatistics() {}
        public void addEvent(Event e);
        public EventStatistics merge(EventStatistics toMerge);
    }
    

    然后 you can do

    groupingBy(Event::getLocation, Collector.of(EventStatistics::new, EventStatistics::accept, EventStatistics::merge));
    

    这里,无参数构造函数是 Supplier 这个 accept accumulator ,以及 merge combiner