Context:
I want to use the function computeIfAbsent
on a Map
. But, I get a compilation error when I use
- method reference and the key is a
String
.
I get no compilation error when I use
- method reference and the key is an
Integer
. - lambda and the key is a
String
.
Illustration:
The following statements are legal:
Map<Integer, List<Long>> map = new HashMap<>();
Integer key = Integer.valueOf(0);
Long value = Long.valueOf(2);
map.computeIfAbsent(key, ArrayList::new).add(value); // No compilation error
The following statements are illegal:
Map<String, List<Long>> map = new HashMap<>();
String key = "myKey";
Long value = Long.valueOf(2);
map.computeIfAbsent(key, ArrayList::new).add(value); // Compilation error: The type ArrayList does not define ArrayList(String) that is applicable here
The following statements are legal:
Map<String, List<Long>> map = new HashMap<>();
String key = "myKey";
Long value = Long.valueOf(2);
map.computeIfAbsent(key, x -> new ArrayList<>()).add(value); // No compilation error
Question:
I don't get why a String
as key is that special when combined with method reference. Any idea?