I have a map
Map<Integer, List<Person>> personsById and a predicate function callbak
(person) -> person.getPersonID() > 10 && person.blabla() !=null I need to filter the map based on the predicate and I came up with below code which doesn't modify the List
map.entrySet().stream() .filter(entry -> entry.getValue().stream().anyMatch(predicate)) .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue)) However the above code doesnt actually filter the List ext: {id: 100, [{personID: 100}, {personID: 50}, {personID: 2}] I can still seee personID: 2 in the list. Is there a way I can modify the value in the list to return filtered List or persons?. Any pointers on it in java 8 will be greatly useful.
P.s: Plz ignore any typos in the typed code I came up with.
Edit: I got the answer
map.entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().stream().filter(predicate).collect(Collectors.toList())))
.filter(entry -> entry.getValue().stream().anyMatch(predicate))you're basically saying "given a map entry, create a stream from the entry value (a List<Person> in this case) then if any of the people in the list match the provided predicate then retain the entire entry". hence were getting unexpected results.