更新时间:2021-08-19 15:05:29
不确定我是否正确理解了这个问题,但是类似的方法可能有效. 尚未检查所有语法,因此某处可能存在一些错误.
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));