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:
Turns out to be a little different answer, but we can do it using flatMapping collector provided with Java9.
this is your station class -
class Station {
public List getRadioList() {
return radioList;
}
private List radioList = new ArrayList<>();
}
And the list of stations you want to map -
List list = new ArrayList<>();
Below is the code that will let you map it using flatMapping collector.
list.stream().collect(Collectors.flatMapping(station ->
station.getRadioList().stream()
.map(radio ->Map.entry( radio, station)),
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue), (radio, radio2) -> radio2)));
If you don't want to use flatMapping, you can actually first use FlatMap and then collect, it will be more readable.
list.stream().flatMap(station -> station.getRadioList().stream().map(s -> Map.entry(s, station)))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (radio, radio2) -> radio2)));