Home > front end >  How to check if hashmap contains the key before getting it in the shortest way?
How to check if hashmap contains the key before getting it in the shortest way?

Time:10-08

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.

CodePudding user response:

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.

CodePudding user response:

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);
  •  Tags:  
  • java
  • Related