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?
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.
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.
The ConcurrentHashMap operations are thread-safe. ConcurrentHashMap doesn't allow null for keys and values.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With