I have implemented the following example:
Map<String, List<Event>> map = events.getItems().stream()
.collect(Collectors.groupingBy(Event::getStatus, Collectors.toList()));
How can I get an output of Map<String, List<EventDto>> map
instead?
An EventDto
can be obtained by executing an external method which converts an Event
to an EventDto
. For example - this::convertFromEventToEventDto
.
toList. Returns a Collector that accumulates the input elements into a new List . There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier) .
For instance, Collectors. toList() method can return an ArrayList or a LinkedList or any other implementation of the List interface. To get the desired Collection, we can use the toCollection() method provided by the Collectors class.
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.
Java Stream collect() is mostly used to collect the stream elements to a collection. It's a terminal operation. It takes care of synchronization when used with a parallel stream. The Collectors class provides a lot of Collector implementation to help us out.
You need a mapping
Collector
to map the Event
elements to EventDto
elements :
Map<String, List<EventDto>> map =
events.getItems()
.stream()
.collect(Collectors.groupingBy(Event::getStatus,
Collectors.mapping(this::convertFromEventToEventDto,
Collectors.toList())));
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