我正在尝试从 Map
中移动一个项目在Map
之外.
我正在尝试从 List
中获取 rowIdentifier下面:
List<Map<Object,Object>>
// [{"rowIdentifier": "s5", "rowKey1": 5, "rowKey2": 7},{"rowIdentifier": "s7", "rowKey1": 9, "rowKey2": 9}]
进入结果Map<Map<Object,Object>>
// {"s5": {"rowKey1": 5, "rowKey2": 7}, "s7": {"rowKey1": 9, "rowKey2": 9}
我有点难以理解 groupingBy
和 collect(Collectors.mapping)
与 Collectors.toMap
(我不确定我是否理解 Java Stream
中“映射”与“toMap”函数之间的区别。或者我什至需要它。
DictByRowIdentifier[r["rowIdentifier"]] 是我计划稍后调用它的方式。
网上很多例子好像都是简单的收集到一个List
或 Set
.他们似乎没有把它扔回另一个Map
所以很难找到例子。
最佳答案
要回答您的直接问题,您需要 toMap()
, 两次:
List<Map<String, String>> listOfMaps = new ArrayList<>(); // populated elsewhere
Map<String, Map<String, String>> mapOfMaps = listOfMaps.stream()
.collect(Collectors.toMap(m -> m.get("rowIdentifier"),
m -> m.entrySet().stream().filter(e -> !e.getKey().equals("rowIdentifier"))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))));
我将类型更改为 String
,因为这就是它们的本质,它使所有内容都可以在没有警告的情况下编译。
关于java - 使用 Java Streams 从 map 列表中提取一个键,并创建一个 map 的 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42683825/