英文:
Java 8 Stream API to get specific value
问题
以下是翻译好的部分:
"Having the below JSON structured value. I would like to get the value from the "KEY" in List of Strings"
"Expected Output (List of String):"
"Tried this and it is working with one layer, not with second layer"
"final Map<String, Map<String, String>> value = document.get("Test", Collections.emptyMap()); return value.values().stream() .map(valueMap -> valueMap.get("KEY")) .collect(Collectors.toList());"
英文:
Having the below JSON structured value. I would like to get the value from the "KEY" in List of Strings
"Test": {
"ONE": {
"First_Layer": {
"KEY": "VALUE_1"
},
"First_Layer_1": {
"KEY": "VALUE_2"
}
},
"TWO": {
"First_Layer_2": {
"KEY": "VALUE_3"
}
}
}
Expected Output (List of String):
[VALUE_1, VALUE_2, VALUE_3]
Tried this and it is working with one layer, not with second layer
final Map<String, Map<String, String>> value = document.get("Test", Collections.emptyMap());
return value.values().stream()
.map(valueMap -> valueMap.get("KEY"))
.collect(Collectors.toList());
答案1
得分: 2
你的数据应该反序列化为 Map<String, Map<String, Map<String, String>>>
然后你可以使用 flatMap
来扁平化第一层
List<String> res = data
.entrySet()
.stream()
.flatMap(m -> m.getValue().entrySet().stream())
.map(v -> v.getValue().get("KEY"))
.collect(Collectors.toList());
英文:
Your data should deserialize into Map<String, Map<String, Map<String, String>>>
Then you can use flatMap
to flat the first layer
List<String> res = data
.entrySet()
.stream()
.flatMap(m -> m.getValue().entrySet().stream())
.map(v-> v.getValue().get("KEY"))
.collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论