I've got entity/form called Time with fields:
Integer id;
Date date;
Integer value;
And another form called SummaryForm
String title;
String descr;
List<Object> newList;
How to improve map usage with Java 8 interface. Right now I've got an if statement:
if (map.containsKey(key)) {
map.get(key).newList().add(new SummaryForm(time.getDate(), time.getValue()));
}
Is there any simple way to improve it to avoid if statements, t with map.containsKey? In my opinion, I need something like putIfPresent, but it seems there is an only putIfAbsent method.
There are several new methods in Java 8 that extend among other things the Map interface, thanks to the introduction of default methods (so backwards compatibility is kept).
There's no putIfPresent, but there are replace() method(s) which would work that way.
However it looks like your looking for computeIfPresent here:
map.computeIfPresent(key, (k, value) -> {
value.newList().add(new SummaryForm(time.getDate(), time.getValue());
return value;
})
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