[英]Convert Map<String, Object> to Map<String, Set<Object>> with filter and streams
[英]convert from Map<Object,Set<Object>> to Map<String,Set<String>>
我有一个地图Map<String, Set<String>>
Map<String, Set<String> result = map.entrySet().parallelStream().collect(
Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toSet())));
我想将其转换为Map<String, Set<String>>
。 通过将值分组并交换键和值的位置。
但是这条线给我
Type mismatch: cannot convert from Map<Object,Set<Object>> to Map<String,Set<String>>
您在这里遇到的问题是您要创建的地图的类型是:
Map<Set<String>, Set<String>>
不是Map<String, Set<String>>
。
因此,您需要首先扩展地图的值,例如:
Map<String, Set<String>> collect = map.entrySet()
.parallelStream()
// Expand (k, {v1, v2, v3}) to [(v1, k), (v2, k), (v3, k)]
.flatMap(e -> e.getValue().stream().map(ee -> new SimpleEntry<>(ee, e.getKey())))
.collect(
Collectors.groupingBy(
Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toSet())));
除非您真的需要并行处理,否则我认为使用循环会容易得多:
Map<String, Set<String>> collect = new HashSet<>();
for (Map.Entry<String, Set<String>> entry : map.entrySet()) {
for (String v : entry.values()) {
collect.computeIfAbsent(v -> new HashSet<>())
.add(entry.getKey()));
}
}
这是一个考虑初始映射为“对象到对象”的示例。 根据需要进行调整。
Map<Object,Object> map = new HashMap<>();
Map<String, Set<String>> result = map
.entrySet()
.parallelStream()
.collect(Collectors.groupingBy(entry -> (String) entry.getKey(),
Collectors.mapping(entry -> (String) entry.getKey(), Collectors.toSet())));
您的代码的问题是Map.Entry::getKey
返回一个对象,而不是字符串。
为了避免混淆,我在回答我的问题。 感谢@AndyTurner @alexrolea指出了解决方案。
Map<Set<String>, Set<String>> result = map.entrySet().parallelStream()
.collect(
Collectors.groupingBy(entry -> (Set<String>) entry.getValue(),
Collectors.mapping(entry -> entry.getKey(), Collectors.toSet())));
我必须将Map.Entry::getValue
替换为entry -> (Set<String>) entry.getValue()
然后也entry -> (Set<String>) entry.getValue()
另一个。
这有助于我按值对地图进行分组并将其用作键。 谢谢@nullpointer
实际上,这也有效。 问题是我没有返回正确的数据类型。
Map<Set<String>, Set<String>> result = map.entrySet().parallelStream()
.collect(
Collectors.groupingBy(Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey, Collectors.toSet())));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.