Blueshark
Blueshark

Reputation: 41

HashMap + Lambda. How to add a new value <List> if is null

I would like to "translate" this code to use it with Java 8 new features. Lambda, map.compute.

But there is an error :

Type mismatch: cannot convert from boolean to ArrayList<DayDetailsBean>

Any ideas guys?

Upvotes: 4

Views: 1050

Answers (1)

Jorn Vernee
Jorn Vernee

Reputation: 33865

You can use computeIfAbsent. Which:

If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.

returns the current (existing or computed) value associated with the specified key, or null if the computed value is null

map.computeIfAbsent(i, k -> new ArrayList<DayDetailsBean>()).add(dayDetails);

Upvotes: 6

Related Questions