我有一个嵌套的 HashMap
这种形式:
{key1=val1, key2=val2,
key3=[
{key4=val4, key5=val5},
{key6=val6, key7=val7}
]
}
我现在想展平那张 map ,以便所有条目都在同一层上:
{key1=val1, key2=val2, key4=val4, key5=val5,key6=val6, key7=val7}
当我尝试
map.values().forEach(map.get("key3")::addAll);
作为described in this post ,我收到以下错误:
invalid method reference
cannot find symbol
symbol: method addAll(T)
location: class Object
where T is a type-variable:
T extends Object declared in interface Iterable
是否有任何通用的方法来展平任何给定的 Map
?
最佳答案
不确定我是否正确理解了这个问题,但这样的事情可能会奏效。 还没有检查所有语法,所以可能某处有错误。
Stream<Map.Entry<String, String>> flatten(Map<String, Object> map) {
return map.entrySet()
.stream()
.flatMap(this::extractValue);
}
Stream<Map.Entry<String, String>> extractValue(Map.Entry<String, Object> entry) {
if (entry.getValue() instanceof String) {
return Stream.of(new AbstractMap.SimpleEntry(entry.getKey(), (String) entry.getValue()));
} else if (entry.getValue() instanceof Map) {
return flatten((Map<String, Object>) entry.getValue());
}
}
然后你可以这样做:
Map<String, String> flattenedMap = flatten(yourmap)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
关于java - 如何展平 HashMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54183766/