0

I'm coming from C++ and I feel a little bit frustrated and confused. I was googling for help for a while and I still can't find an answer, so I am here.

How in Java can I implement a NavigableMap<String, ?> where at the question mark is an object which can be called with two arguments and then return a value.

I would like it to look like so:

NavigableMap<String, SomeFunctorClass> container;

// I also don't know how to write a lambda thing in java, so it won't work.
// [](double a, double b) -> double { return a + b; } // in C++
container.put("add", (double a, double b) -> { return a + b; });

// Expected to be 10.
double result = container.get("add")(4, 6);
Mureinik
  • 297,002
  • 52
  • 306
  • 350

2 Answers2

1

The closest thing Java offers out of the box is probably a BiFunction.

You still won't be able to call it directly with () like you'd do on a C++ functor, but you can call its apply method:

NavigableMap<String, BiFunction<Double, Double, Double>> container = new TreeMap<>();
container.put("add", (a, b) -> a + b);
double result = container.get("add").apply(4.0, 6.0);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

The equivalent in java is a BiFunction:

NavigableMap<String, BiFunction<Double, Double, Double>> container;
container.put("add", (a, b) -> a + b);

Note that generics in Java cannot be primitive, so you should use the boxed versions (Double for double, Integer for int etc.)

If you need more than 2 parameters (for example a TriFunction), then you'll need to create your own interface since Java standard library doesn't offer more than that (it's not as extensible as C++).

As for the way of calling it:

// Expected to be 10.
double result = container.get("add").apply(4.0, 6.0);
Matteo NNZ
  • 11,930
  • 12
  • 52
  • 89