Java 8 convert List to Lookup Map

前端 未结 9 2057
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 03:29

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:

相关标签:
9条回答
  • 2021-01-12 04:21

    How about:

    radioToStationMap = StreamEx.of(stationList)
            .flatMapToEntry(s -> StreamEx.of(s.getRadioList()).mapToEntry(r -> s).toMap())
            .toMap();
    

    By StreamEx

    0 讨论(0)
  • 2021-01-12 04:22

    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)));
    
    1. We will convert them to Map.Entry
    2. We will collect all of them together with flatmapping collector

    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)));
    
    0 讨论(0)
  • 2021-01-12 04:24

    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())));
    
    0 讨论(0)
提交回复
热议问题