Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use plus operator of integer as BiFunction

Tags:

java

java-8

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.

like image 323
Alex Avatar asked Sep 15 '16 14:09

Alex


1 Answers

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

like image 151
Sergei Rybalkin Avatar answered Sep 30 '22 18:09

Sergei Rybalkin