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);
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);