Assume that I have this map :
String str = ResourceUtils.getResourceAsString("/myjson.json");
ObjectMapper mapper = new ObjectMapper();
TypeReference rootType = new TypeReference<List<Map<String, Object>>>() {
};
List<Map<String, Object>> root = mapper.readValue(str, rootType);
Map<String, Object> map = root.stream().reduce(new LinkedHashMap<>(), (dest, m2) -> {
dest.put(m2.get("map").toString(), m2.get("values"));
return dest;
});
Where str is a json file that contains "map" and "values" fields, map is a string and values is an array of string.
How can I retrieve a list (or array) of Strings that contains values of filtered keys? I am at this point for the moment :
List<String> startWords = map.entrySet()
.stream()
.filter(x -> x.getKey().equalsIgnoreCase("x") || x.getKey().equalsIgnoreCase("y"))
I know that there will be a .collect(Collectors::toList()) at the end, but if I try a flatMap after my filter, I have an Stream inferred error.
Thanks!
EDIT: The output intended is a list like this:
List<String> list = new ArrayList<>();
list.put("hello");
list.put("world");
You don't want to use flatMap
but simply map
. It should look like this:
List<String> startWords = map.entrySet()
.stream()
.filter(x -> x.getKey().equalsIgnoreCase("x") || x.getKey().equalsIgnoreCase("y"))
.map(x -> x.getValue())
.collect(Collectors.toList())
You use flatMap
when you want to "flatten" some data structure. For example if you can a List of Lists then you will use flatMap
to get a single stream of all elements.
you must add a map before collect, like this :
List<Object> startWords = map.entrySet()
.stream()
.filter(x -> x.getKey().equalsIgnoreCase("x") || x.getKey().equalsIgnoreCase("y"))
.map(x -> x.getValue())
.collect(Collectors.toList());
and the map depend to what you need : getKey or getValue
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.