Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the contents of a list which is inside a HashMap value using Java 8 stream

I have a HashMap with the following structure. Map<String, Container>

The Container class contains a List. I want to clear the contents of this list so that the list exists but with 0 elements. Later I will put values in it again.

The replaceAll() expects a BiFunction. Due to this the following is giving compilation error because return type of clear() is void:

personMap.replaceAll((k,v) -> v.getMyList().clear());

like image 494
Sumit Avatar asked Dec 23 '25 00:12

Sumit


2 Answers

You can use this:

map.values().forEach(i -> i.getMyList().clear());

Alternatively you can use this:

map.values().stream()
        .map(Container::getMyList)
        .forEach(List::clear);
like image 138
Samuel Philipp Avatar answered Dec 24 '25 14:12

Samuel Philipp


Iterating your Map with forEach will require a BiConsumer<? super K, ? super V> (where K and V are the key and value types of your Map), which will ultimately allow you to invoke void methods on the elements.

E.g.

personMap.forEach((k,v) -> v.getMyList().clear());
like image 35
Mena Avatar answered Dec 24 '25 13:12

Mena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!