Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 793
g0c00l.g33k Avatar asked Mar 15 '16 13:03

g0c00l.g33k


People also ask

How do I get a key value from ConcurrentHashMap?

The keys() method of ConcurrentHashMap class in Java is used to get the enumeration of the keys present in the hashmap. Parameters: The method does not take any parameters. Return value: The method returns an enumeration of the keys of the ConcurrentHashMap.

How do you atomically update a value in ConcurrentHashMap?

The compute(Key, BiFunction) method of ConcurrentHashMap class is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping is found). This method is used to atomically update a value for given key in ConcurrentHashMap.

Is ConcurrentHashMap values thread-safe?

The ConcurrentHashMap operations are thread-safe. ConcurrentHashMap doesn't allow null for keys and values.


1 Answers

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);
like image 92
Tunaki Avatar answered Sep 26 '22 07:09

Tunaki