I have a stream of Event
s
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?
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.
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.
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.
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.
All you need is collectingAndThen:
Map<Location, EventStatistics> result =
events.stream()
.collect(Collectors.groupingBy(Event::getLocation,
Collectors.collectingAndThen(
Collectors.toList(),
EventStatistics::new)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With