eazy
eazy

Reputation: 5

Using computeIfAbsent method in java?

I get the general idea behind it e.g puts new set in map if not there but actually getting it to work has been difficult! so i currently have something like this. the example in javadocs isnt quite sinking

if (!result.containsKey(someID)) {
    hashy = new HashSet<>();
    result.put(someID, hashy);
} else {
    hashy = result.get(someID);
}

as you can see from the above if the result (which is a map of <String, Set>) dosnt contain someID then we are putting someID and the new hashset in it.

How would i use the computeIfAbsent function here instead ?

hashy = new HashSet<>();

result.computeIfAbsent(someID, k-> result.put(someID, hashy ));

ive tried this but it dosnt seem to be working

any ideas ?

Upvotes: 0

Views: 664

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70297

The point of computeIfAbsent is that you don't construct the new object unless you actually need it, and you also don't explicitly call put. computeIfAbsent does all of that for you.

So the equivalent to your original hashy code

if (!result.containsKey(someID)) {
    hashy = new HashSet<>();
    result.put(someID, hashy);
} else {
    hashy = result.get(someID);
}

is merely

hashy = result.computeIfAbsent(someID, _ -> new HashSet<...>());

Note that, depending on your use case, Java may or may not be able to infer the generic type of the HashSet, so you may have to specify the type in the angled brackets explicitly.

Upvotes: 6

Related Questions