I have a map in which I want to count things. Previous to java 8, I would have had to put a zero in the map for every key, before I could so something like map.put(key, map.get(key)+1)
.
Since Java 8, I can now use Map's merge method like in the following example:
public class CountingMap {
private static final Map<Integer, Integer> map = new HashMap<> ();
public static Integer add (final Integer i1,
final Integer i2) {
return i1 + i2;
}
public static void main (final String[] args) {
map.merge (0, 1, CountingMap::add);
System.out.println (map); //prints {0=1}
map.merge (0, 1, CountingMap::add);
System.out.println (map); //prints {0=2}
}
}
My question is, can I pass a reference to the + operator of Integer as BiFunction instead of having to declare my own add function?
I already tried things like Integer::+
, Integer::operator+
, but none of those works.
EDIT: As Tunaki pointed out, I could've used Integer::sum
instead. Still, I'm wondering whether there is a possibility to pass an operator directly as reference.
There is no way to pass +
operator in Java.
You can instantiate add
directly in method call.
map.merge (0, 1, (i, j) -> i + j);
Or assign variable:
BiFunction<Integer, Integer, Integer> add = (i, j) -> i + j;
Or the same things with Integer::sum
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With