Filter ConcurrentHashMap by value

I am trying to filter out ConcurrentHashMap<String, LinkedList<String>> by size of LinkedList<String> .

In other words, I want to filter items in ConcurrentHashMap , where the LinkedList<String> larger than 4. How can I do this using Java 8?

+6
source share
1 answer

If you have a ConcurrentMap , you can simply create a stream of your records by calling entrySet() and then stream() and save the records in which the value is longer than 4 by applying filter . Finally, you can reassemble it in ConcurrentMap with the built-in Collectors.toConcurrentMap .

 ConcurrentMap<String, LinkedList<String>> map = new ConcurrentHashMap<>(); ConcurrentMap<String, LinkedList<String>> result = map.entrySet() .stream() .filter(e -> e.getValue().size() > 4) .collect(Collectors.toConcurrentMap(Map.Entry::getKey, Map.Entry::getValue)); 

Alternatively, you can do this locally by changing the map with

 map.values().removeIf(l -> l.size() <= 4); 
+12
source

All Articles