Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: not-void methods as map values

I have some code like this:

public class A {
    private final Map<String, Runnable> map = new HashMap<>();
    public A() {
        map.put("a", () -> a());
        map.put("b", () -> b());
    }
    public int a() {
        return 1;
    }
    public int b() {
        return 2;
    }
    public int c(String s) {
        // map.get(s).run(); <= returns void, but
        //                      I need the result of the 
        //                      function paired to the string.
        // What TODO?
    }
}

I have not-void functions (a(), b()) as values of a map, paired to Strings. I need to run the functions and get the result of the functions, and return it in the function c(). The run() function returns void, so I can't get the value from it. Is there any way to do this?

like image 727
Display Name Avatar asked Sep 23 '26 10:09

Display Name


1 Answers

What you want to do here is to return an int value from the method. For that, you can't use a Runnable as run() doesn't return a value.

But you can use an IntSupplier, which is a functional interface representing a function supplying an int value. Its functional method getAsInt is used to return the value.

public class A {
    private final Map<String, IntSupplier> map = new HashMap<>();
    public A() {
        map.put("a", () -> a()); // or use the method-reference this::a
        map.put("b", () -> b()); // or use the method-reference this::b
    }
    public int a() {
        return 1;
    }
    public int b() {
        return 2;
    }
    public int c(String s) {
        return map.get(s).getAsInt();
    }
}

Additionally, if you don't want to return a primitive but an object MyObject, you can use the Supplier<MyObject> functional interface (or Callable<MyObject> if the method to call can throw a checked exception).

like image 101
Tunaki Avatar answered Sep 26 '26 04:09

Tunaki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!