如何将方法引用传递给Triple?

时间:2019-01-10 12:01:40

标签: java function generics

我有一个三元组列表,例如

import org.apache.commons.lang3.tuple.ImmutableTriple;

final HashMap<String, ImmutableTriple<String, String, Function<String, String>>> olMap = new HashMap();

我想添加

olMap.put("start", new ImmutableTriple("str1", "str2", MyClass::minusOne));

我收到以下错误:

The constructor ImmutableTriple(String, String, MyClass::minusOne) is undefined

private static String minusOne(String count) {
    String ret = count;
    if (count != null) {
        try {
            ret = (Integer.parseInt(count) - 1) + "";
        } catch (final Exception e) {
            // nothing to do cuz input wasn't a number...
        }
    }
    return ret;
}

,但是不知何故我无法正确获得签名。最后但并非最不重要的一点是如何最终调用该方法?即这是正确的语法吗?

ol.get("start").right.apply("100")

更新:

我找到了正确的语法:

final HashMap<String, Triple<String, String, Function<String, String>>> olMap = new HashMap();
olMap.put("start", new Triple.of("str1", "str2", MyClass::minusOne));

感谢您的帮助和保证-否则我找不到它

1 个答案:

答案 0 :(得分:1)

[ "110":{ "id":110, "name":"example name 1" }, "220":{ "id":220, "name":"example name 2" } ] 可以是正确的Java语法。

您尝试将new Triple.of(...)作为MyClass::minusOne进行传递,由于它不是功能接口,因此出现了编译错误。

确保您没有原始类型:

Object

正确的选项将指定完整的类型参数列表:

ImmutableTriple t = new ImmutableTriple("str1", "str2", MyClass::minusOne);
HashMap m = new HashMap();

或使用Triple<String, String, Function<String, String>> t1 = Triple.<String, String, Function<String, String>>of("str1", "str2", MyClass::minusOne); Triple<String, String, Function<String, String>> t2 = new ImmutableTriple<String, String, Function<String, String>>("str1", "str2", MyClass::minusOne); 使其自动解决:

<>