7

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
Sergii
  • 7,044
  • 14
  • 58
  • 116
  • 1
    What is `EventDto` and how is it related to the elements of your Stream? – Eran Mar 20 '17 at 08:32
  • @eran I should use external function to convert `Event` to `EventDto`. I think in explanation can be used any name if you with, or for example `this::convertFromEventToEventDto` – Sergii Mar 20 '17 at 08:37
  • 1
    Does `EventDto` have a status? – shmosel Mar 20 '17 at 18:36
  • I tried this idea also, but it is different story because of some restrictions and I should not change `EventDto` – Sergii Mar 20 '17 at 19:40

1 Answers1

15

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())));
Eran
  • 387,369
  • 54
  • 702
  • 768