Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Group By then Map

I have a stream of Events

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

And a statistics class EventStatistics

public class EventStatistics {
    // Stats properties e.g. turnout standard deviation/median

    public EventStatistics(List<Event> events) {
        // Generate stats
    }
}

I need to group all the events by location & create a map of location and event statistics Map<Location, EventStatistics>

The group by is just:

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

I know there is an overloaded groupingBy(function, collector) collector. Can I use somehow this to generate my Map<Location, EventStatistics> in a single stream?

like image 992
Eduardo Avatar asked Mar 10 '18 08:03

Eduardo


People also ask

What is groupingBy in Java?

The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed. This method provides similar functionality to SQL's GROUP BY clause.

How does Groupby work in Java 8?

In Java 8, you retrieve the stream from the list and use a Collector to group them in one line of code. It's as simple as passing the grouping condition to the collector and it is complete. By simply modifying the grouping condition, you can create multiple groups.

What is a flatMap in Java 8?

In Java 8 Streams, the flatMap() method applies operation as a mapper function and provides a stream of element values. It means that in each iteration of each element the map() method creates a separate new stream. By using the flattening mechanism, it merges all streams into a single resultant stream.

What is streams in Java?

A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.


1 Answers

All you need is collectingAndThen:

Map<Location, EventStatistics> result = 
    events.stream()
          .collect(Collectors.groupingBy(Event::getLocation,
                                         Collectors.collectingAndThen(
                                             Collectors.toList(), 
                                             EventStatistics::new)));
like image 185
JB Nizet Avatar answered Sep 30 '22 19:09

JB Nizet