Java 8 convert List to Lookup Map

前端 未结 9 2115
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  旧时难觅i
    2021-01-12 04:19

    I don't think that you can do it in more concise way using Collectors, as compared to mixed solution like

        stationList.stream().forEach(station -> {
            for ( Long radio : station.getRadioList() ) {
                radioToStationMap.put(radio, station);
            }
        });
    

    or

        stationList.forEach(station -> {
            station.getRadioList().forEach(radio -> {
                radioToStationMap.put(radio, station);
            });
        });
    

    (you can call .forEach directly on collections, don't need to go through .stream())

    Shortest fully 'functional' solution I was able to come up with would be something like

     stationList.stream().flatMap(
         station -> station.getRadioList().stream().map(radio -> new Pair<>(radio, station)))
     .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
    

    using any of the Pair classes available in third party libraries. Java 8 is very verbose for simple operations, compared to dialects like Xtend or Groovy.

提交回复
热议问题