Java 8 convert List to Lookup Map

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

    We can save the intermediate step of collectiong to a Map by transforming directly to a Stream of SimpleEntry, for example:

    Map result = stationList.stream()
                    .flatMap(station -> station.getRadioList().stream().map(radio -> new SimpleEntry<>(radio, station)))
                    .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue));
    

提交回复
热议问题