地图<字符串,列表<字符串>>配对< String,String> [英] Map<String,List<String>> to Pair<String,String>

查看:164
本文介绍了地图<字符串,列表<字符串>>配对< String,String>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Java 8 Stream API如何将 Map 平展为 Pair 列表左对值是地图的位置键?

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)


推荐答案

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

这篇关于地图&LT;字符串,列表&LT;字符串&GT;&GT;配对&lt; String,String&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆