Java 8 convert List to Lookup Map

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

    If you are open to using a third-party library, there is the method groupByEach from Eclipse Collections:

    Multimap multimap = 
        Iterate.groupByEach(stationList, Station::getRadioList);
    

    This can also be written using Java 8 Streams with the Collectors2 utility from Eclipse Collections:

    Multimap multimap =
            stationList.stream().collect(
                    Collectors2.groupByEach(
                            Station::getRadioList,
                            Multimaps.mutable.list::empty));
    

    Note: I am a committer for Eclipse Collections.

提交回复
热议问题