Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improve if containsKey in map by java 8 interface

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.

like image 793
degath Avatar asked Oct 25 '25 23:10

degath


1 Answers

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;
})
like image 83
Eugene Avatar answered Oct 27 '25 13:10

Eugene



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!