1

I wonder why the Map method computeIfAbsent take a Function to calculate the value and not a Supplier.

map.computeIfAbsent(key, key::toString); // Supplier<V>
map.computeIfAbsent(key, k -> k.toString()); // Function<K, V>

Here, the keys "key" and "k" are exactly the same Object

It's particularly strange when the key isn't used. Like in multi map :

// Have to do this :
multiMap.computeIfAbsent(key, __ -> new ArrayList<>()).add(value);
// instead of :
multiMap.computeIfAbsent(key, ArrayList::new).add(value);

Why did Java developers do this ?

Didi Bear
  • 356
  • 3
  • 13
  • Because the computation function may be invoked at an arbitrary later point. – Boris the Spider Nov 29 '16 at 19:30
  • How would you get a missing key in a supplier in case of need? – Lyubomyr Shaydariv Nov 29 '16 at 19:31
  • 3
    I'd guess it's so you don't have to construct a new lambda for each key. Also, if `key` is not simply a variable, it avoids having to store the expression in a variable in order to ensure the same value in the first parameter and the lambda. – Andy Turner Nov 29 '16 at 19:32
  • 4
    [This thread](http://mail.openjdk.java.net/pipermail/lambda-dev/2013-July/010533.html) on the mailing list will probably answer why... There are lots of replies, but [this one](http://mail.openjdk.java.net/pipermail/lambda-dev/2013-July/010535.html) seems relevant... – Tunaki Nov 29 '16 at 19:47
  • 6
    Because in the real world, sometimes the key is needed as an input into creating the computed value. – Brian Goetz Nov 29 '16 at 20:20

0 Answers0