I have a list of Station, in each Station there is a list of radios. I need to create a lookup Map of radio to Station. I know how to use Java 8 stream forEach to do it:
I don't think that you can do it in more concise way using Collectors, as compared to mixed solution like
stationList.stream().forEach(station -> {
for ( Long radio : station.getRadioList() ) {
radioToStationMap.put(radio, station);
}
});
or
stationList.forEach(station -> {
station.getRadioList().forEach(radio -> {
radioToStationMap.put(radio, station);
});
});
(you can call .forEach directly on collections, don't need to go through .stream()
)
Shortest fully 'functional' solution I was able to come up with would be something like
stationList.stream().flatMap(
station -> station.getRadioList().stream().map(radio -> new Pair<>(radio, station)))
.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
using any of the Pair classes available in third party libraries. Java 8 is very verbose for simple operations, compared to dialects like Xtend or Groovy.