20

I just recently found myself wanting a version of putIfAbsent(...) in java.util.Map that you can supply some kind of factory method to, to instantiate an Object if it's not already present. This would simplify a lot of code.

Here is my modified interface:

import java.util.Map;
import java.util.function.Supplier;

/**
 * Extension of the Map Interface for a different approach on having putIfAbsent
 * 
 * @author Martin Braun
 */
public interface SupplierMap<K, V> extends Map<K, V> {

    public default V putIfAbsent(K key, Supplier<V> supplier) {
        V value = this.get(key);
        if(value == null) {
            this.put(key, value = supplier.get());
        }
        return value;
    }

}

Now my question: Is there another (easier) way of doing this or have I just overlooked something in the Java API?

4
  • 4
    FWIW, Map#putIfAbsent was added with Java8.
    – merours
    Nov 25, 2014 at 13:00
  • in Java 1.8 there is V putIfAbsent(K key, V value) Nov 25, 2014 at 13:00
  • 1
    I know, but it only allows to provide a Object instead of a Supplier method. Nov 25, 2014 at 13:00
  • what's wrong with above code. I think it should work.
    – SMA
    Nov 25, 2014 at 13:01

2 Answers 2

22

Isn't computeIfAbsent what you want?

If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.

Implementation is something like:

if (map.get(key) == null) {
    V newValue = mappingFunction.apply(key);
    if (newValue != null) {
         map.put(key, newValue);
    }
}

So it's not exactly the Supplier<V> signature you've posted but close to that. Having key as argument in the mapping function definitely makes sense.

6
  • Ah. I overlooked that one. Thanks :) Nov 25, 2014 at 13:01
  • Yep. The key as argument makes more sense, that's right. I will accept this answer as soon as I can. Nov 25, 2014 at 13:06
  • Any solution for Java 7 users?
    – shlatchz
    Nov 15, 2016 at 16:37
  • @shlatchz Not with standard Map.
    – lexicore
    Nov 15, 2016 at 20:19
  • @lexicore, so Android programmers don't have any other way to do this?
    – shlatchz
    Nov 15, 2016 at 22:49
2

computeIfAbsent is not a 1:1 replacement for putIfAbsent because constraints for the returned value do not match. While putIfAbsent returns null when a new entry is created, computeIfAbsent always return the assigned value.

A default implementation as suggested above with a call to get and then put works, but it requires two lookups in the map, which destroys the idea of a performant in-situ replacement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.