Java:not-void方法作为map值

Dis*_*ame 3 java methods dictionary functional-programming interface

我有一些像这样的代码:

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?
    }
}
Run Code Online (Sandbox Code Playgroud)

我没有 - 函数(a(),b())作为地图的值,与字符串配对.我需要运行函数并获取函数的结果,并在函数中返回它c().该run()函数返回void,所以我不能得到它的价值.有没有办法做到这一点?

Tun*_*aki 6

你想要做的是int从方法返回一个值.为此,您不能使用a Runnable作为run()不返回值.

但是你可以使用an IntSupplier,它是一个表示提供int值的函数的函数接口.其功能方法getAsInt用于返回值.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,如果您不想返回原语而是返回对象MyObject,则可以使用Supplier<MyObject>功能接口(或者Callable<MyObject>如果要调用的方法可以抛出已检查的异常).