Tengo una lista de Emisoras, en cada Emisora hay una lista de radios. Necesito crear un mapa de búsqueda de radio a estación. Sé cómo usar Java 8 stream forEach para hacerlo:
stationList.stream().forEach(station -> { Iterator<Long> it = station.getRadioList().iterator(); while (it.hasNext()) { radioToStationMap.put(it.next(), station); } }); Pero creo que debería haber una forma más concisa como usar Collectors.mapping() .
¿Alguien puede ayudar?
Esto debería funcionar y no necesita terceros.
stationList.stream() .map(s -> s.getRadioList().stream().collect(Collectors.toMap(b -> b, b -> s))) .flatMap(map -> map.entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));Con base en la pregunta, considerando las entidades Radio y Station definidas como:
@lombok.Getter class Radio { ...attributes with corresponding 'equals' and 'hashcode' } @lombok.Getter class Station { List<Radio> radios; ... other attributes } Se puede crear un mapa de búsqueda desde List<Station> como entrada usando una utilidad como:
private Map<Radio, Station> createRadioToStationMap(final List<Station> stations) { return stations.stream() // create entries with each radio and station .flatMap(station -> station.getRadios().stream() .map(radio -> new AbstractMap.SimpleEntry<>(radio, station))) // collect these entries to a Map assuming unique keys .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); } Ligeramente diferente de este comportamiento, si para el mismo (igual) elemento de Radio en varias Station , uno quiere agrupar todas esas estaciones, se puede lograr usando groupingBy en lugar de toMap como:
public Map<Radio, List<Station>> createRadioToStationGrouping(final List<Station> stations) { return stations.stream() .flatMap(station -> station.getRadios().stream() .map(radio -> new AbstractMap.SimpleEntry<>(radio, station))) // grouping the stations of which each radio is a part of .collect(Collectors.groupingBy(AbstractMap.SimpleEntry::getKey, Collectors.mapping(AbstractMap.SimpleEntry::getValue, Collectors.toList()))); }Si está abierto a usar una biblioteca de terceros, existe el método groupByEach de Eclipse Collections :
Multimap<Radio, Station> multimap = Iterate.groupByEach(stationList, Station::getRadioList); Esto también se puede escribir usando Java 8 Streams con la utilidad Collectors2 de Eclipse Collections:
Multimap<Radio, Station> multimap = stationList.stream().collect( Collectors2.groupByEach( Station::getRadioList, Multimaps.mutable.list::empty));Nota: Soy un confirmador de Eclipse Collections.