簡體   English   中英

Java:Group By Then Map

[英]Java: Group By then Map

我有一個Event

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)收集器。 我可以用某種方式在單個流中生成Map<Location, EventStatistics>嗎?

所有你需要的是收集和然后

Map<Location, EventStatistics> result = 
    events.stream()
          .collect(Collectors.groupingBy(Event::getLocation,
                                         Collectors.collectingAndThen(
                                             Collectors.toList(), 
                                             EventStatistics::new)));

如果您的EventStatistics能夠接受單個Events而不是完整列表,以及合並兩個統計信息的方法,如

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

那么你可以做到

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

這里,無參數構造函數是Supplieracceptaccumulatormergecombiner

您可以使用Collector.of(...)構建自己的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)
));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM