Map<String,List<String>> to Pair<String,String>

我的未来我决定 提交于 2020-01-23 08:27:34

问题


Using Java 8 Stream API how can I flat a Map to Pair list where left pair value is the map key?

Example: If given map was

1 => {1, 2, 3}
2 => {2, 4}

Then desired output is the stream of five pairs:

(1,1) , (1,2) , (1,3) , (2,2) , (2,4)

回答1:


List<Pair<String, String>> result =
    map.entrySet()
       .stream()
       .flatMap(
           entry -> entry.getValue()
                         .stream()
                         .map(string -> new Pair<>(entry.getKey(), string)))
       .collect(Collectors.toList());


来源:https://stackoverflow.com/questions/32189147/mapstring-liststring-to-pairstring-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!