Alvin
Alvin

Reputation: 8499

How to check if hashmap contains the key before getting it in the shortest way?

Is there any shorter way to find if the key already exists before getting it?

    Map<String, Double> map = new HashMap<>();
    if (map.containsKey("2")) {
        fee.put("2", fee.get("2") + 12.00);
    } else {
        fee.put("2", 12.00);
    }

I want to add up the value.

Upvotes: 0

Views: 99

Answers (2)

Andy Turner
Andy Turner

Reputation: 140319

The most concise way to do this is:

map.merge(key, 12.0, Double::sum);

As described in the Javadoc, this default implementation is equivalent to:

 V oldValue = map.get(key);
 V newValue = (oldValue == null) ? value :
              remappingFunction.apply(oldValue, value);
 if (newValue == null)
     map.remove(key);
 else
     map.put(key, newValue);

where remappingFunction is Double::sum in this case.

Upvotes: 4

deepakchethan
deepakchethan

Reputation: 5600

You can refactor it to use getOrDefault method from Map as follows:

   Map<String, Double> fee = new HashMap<>();
   fee.put("2", fee.getOrDefault("2", 0.0) + 12.00);

Another way of doing it could be using Optionals:

    Map<String, Double> fee = new HashMap<>();
    fee.put("2", Optional.ofNullable(fee.get("2")).orElse(0.0) + 12.00);

Upvotes: 0

Related Questions