使用flatMap将地图列表转换为地图 [英] convert list of map to map using flatMap

查看:115
本文介绍了使用flatMap将地图列表转换为地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用flatMapList<Map<String,String>>合并到Map<String,String>?

这是我尝试过的:

final Map<String, String> result = response
    .stream()
    .collect(Collectors.toMap(
        s -> (String) s.get("key"),
        s -> (String) s.get("value")));
result
    .entrySet()
    .forEach(e -> System.out.println(e.getKey() + " -> " + e.getValue()));

这不起作用.

推荐答案

假定列表中包含的映射中没有冲突的键,请尝试以下操作:

Assuming that there are no conflicting keys in the maps contained in your list, try following:

Map<String, String> maps = list.stream()
    .flatMap(map -> map.entrySet().stream())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

这篇关于使用flatMap将地图列表转换为地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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