本文介绍了如何扁平化HashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我以这种形式嵌套了HashMap
:
{key1=val1, key2=val2,
key3=[
{key4=val4, key5=val5},
{key6=val6, key7=val7}
]
}
我现在想展平该地图,以使所有条目都处于同一级别:
I now want to flatten that map, so that all entries are on the same level:
{key1=val1, key2=val2, key4=val4, key5=val5,key6=val6, key7=val7}
当我尝试
When I try
map.values().forEach(map.get("key3")::addAll);
as described in this post, I get the following error:
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
?
推荐答案
不确定我是否正确理解了这个问题,但是类似的方法可能有效.尚未检查所有语法,因此某处可能存在一些错误.
Not sure if I understood the question correctly, but something like this might work.Haven't checked all the syntax yet, so there might be some mistake somewhere.
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));
这篇关于如何扁平化HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!