Flatten a Map> to Map with stream and lambda

后端 未结 4 602
不知归路
不知归路 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:12

    This should work. Please notice that you lost some keys from List.

    Map> mapFrom = new HashMap<>();
    Map mapTo = mapFrom.entrySet().stream()
            .flatMap(integerListEntry -> integerListEntry.getValue()
                    .stream()
                    .map(listItem -> new AbstractMap.SimpleEntry<>(listItem, integerListEntry.getKey())))
            .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue));
    

提交回复
热议问题