dabadaba dabadaba - 1 year ago 66
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
is constructed with an
, precisely each key in

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()
.collect(Collectors.toMap(Function.identity(), ???));

I have tried
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 Source

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

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