11

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?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
g0c00l.g33k
  • 2,458
  • 2
  • 31
  • 41

1 Answers1

25

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);
Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • Thanks a bunch, that works. One minor correction - `Map> map = new ConcurrentHashMap<>();` otherwise compiler says `getKey` and `getValue` cannot be resolved – g0c00l.g33k Mar 15 '16 at 13:31