Search code examples
javajava-8filteringjava-streamconcurrenthashmap

Filter ConcurrentHashMap by value


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

In other words, I want to filter out elements in ConcurrentHashMap where the size of LinkedList<String> is greater than 4. How would I get it done by Java 8?


Solution

  • If you have a ConcurrentMap, you can simply create a stream of its entries, by calling entrySet() and then stream() and keep the entries where the value has a length greater than 4 by applying a filter. Finally, you can collect that again into a 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 could do it in-place by modifying the map with

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