dabadaba dabadaba - 5 months ago 18
Java Question

Java 8 stream: collecting a map to a map and constructors

I understand how you can process the entries of a map and collect the resulting stream into a different map. But I need to put the value using a constructor to which the previous map's key is passed and I can't figure out how to do it.

The scenario is the following:

I have a

Map<Event, EventSchedule> schedules
, and I want to get a
Map<Event, InverseSchedule>
from it. An
InverseSchedule
is constructed with an
Event
, precisely each key in
schedules
.

This is what I tried so far, and I am just one piece away from finally achieving what I'm after:

Map<Event, InverseSchedule> inverseSchedules = schedules.get()
.keySet()
.stream()
.collect(Collectors.toMap(Function.identity(), ???));


I have tried
InverseSchedule::new
but of course that doesn't work because I am passing no arguments, and I couldn't do it using a lambda either.

I am still struggling to understand these new Java 8 features. I would really appreciate if the answer included the explanation of why it works rather than just providing the missing piece.

Answer

The following would work. Also, schedules.get() is not required.

Map<Event, InverseSchedule> inverseSchedules = schedules
    .keySet()
    .stream()
    .collect(Collectors.toMap(Function.identity(), event -> new InverseSchedule(event));