Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 lambda Collectors.groupingBy with map in Collector.toList()

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.

like image 648
Sergii Avatar asked Mar 20 '17 08:03

Sergii


People also ask

What does collectors toList () do?

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) .

Does collectors toList () return ArrayList?

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.

How does Collector GroupingBy work?

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.

What does collect () do in Java?

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.


1 Answers

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())));
like image 57
Eran Avatar answered Sep 22 '22 03:09

Eran