Java 8 convert List to Lookup Map

前端 未结 9 2063
佛祖请我去吃肉
佛祖请我去吃肉 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: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 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)));
    
    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)));
    

提交回复
热议问题