Reputation: 2161
I have a map of maps - Map> - collection.
I need to filter the map and get the outer map that has a given value for a given key of the inner map.
I tried some combinations, but it is not working.
How do I achieve this.
This is what I have tried
Map<String, Map<String, String>> originalMap = getOriginalMap();
String channelId = "channelIdVal";
Map<String, Map<String, String>> filteredMapForKey = originalMap.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue().entrySet().stream().filter(innerMap -> innerMap.getValue().equalsIgnoreCase(channelId)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))));
Basically, I am expecting the filteredMapForKey to have a single entry whose inner map ( the value of the entry ) to contain a key whose value is channelId
How do I achieve that. The above code is returning the entire original map with same keys but empty inner maps except for the valid one. For the valid map, instead of returning the complete inner map, it is only return the map with the key and value of matching channel id
Thanks
Upvotes: 3
Views: 2661
Reputation: 31868
Seems like there are two things to correct here:
The filter logic to filter in entries instead of filtering them out.
To filter only those outer entries for which inner map satisfies the condition stated.
You can achieve that as:
Map<String, Map<String, String>> filteredMapForKey = originalMap.entrySet()
.stream()
.filter(e -> e.getValue()
.values()
.stream()
.anyMatch(innerMapVal -> innerMapVal.equalsIgnoreCase(channelId)))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
This filters all the outer map entries such that, the inner map for them has a value that is equal(ignoreCase) to the given channelId
and then collects these entries into a similar Map
as the input.
Upvotes: 1