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:
How about:
radioToStationMap = StreamEx.of(stationList)
.flatMapToEntry(s -> StreamEx.of(s.getRadioList()).mapToEntry(r -> s).toMap())
.toMap();
By StreamEx
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<String> getRadioList() {
return radioList;
}
private List<String> radioList = new ArrayList<>();
}
And the list of stations you want to map -
List<Station> 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)));
Just as in Artur Biesiadowski answer i think you must create a list of pair's and then group them, at least if you want to cater for the case that the radios are not unique per station.
In C# you have practical anonymous classes one can use for this, but in Java you would have to define at least the interface of the Pair class
interface Radio{ }
interface Station {
List<Radio> getRadioList();
}
interface RadioStation{
Station station();
Radio radio();
}
List<Station> stations = List.of();
Map<Radio,List<Station>> result= stations
.stream()
.flatMap( s-> s.getRadioList().stream().map( r->new RadioStation() {
@Override
public Station station() {
return s;
}
@Override
public Radio radio() {
return r;
}
} )).collect(groupingBy(RadioStation::radio, mapping(RadioStation::stations, toUnmodifiableList())));