Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
Java 8 convertir lista a mapa de búsqueda

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?

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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));
about 4 years ago · Santiago Trujillo Report

0

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()))); }
about 4 years ago · Santiago Trujillo Report

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!