Flatten a Map> to Map with stream and lambda

后端 未结 4 620
不知归路
不知归路 2020-12-13 02:37

I would like to flatten a Map which associates an Integer key to a list of String, without losing the key mapping. I am curious as tho

4条回答
  •  误落风尘
    2020-12-13 03:23

    You should use flatMap as follows:

    entrySet.stream()
            .flatMap(e -> e.getValue().stream()
                           .map(s -> new SimpleImmutableEntry(e.getKey(), s)));
    

    SimpleImmutableEntry is a nested class in AbstractMap.

提交回复
热议问题