首页 > 解决方案 > 如何将方法引用传递给 Triple?

问题描述

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

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

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

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

感谢您的帮助和安慰 - 否则我不会找到它

标签: javafunctiongenerics

解决方案


new Triple.of(...)可以是正确的 Java 语法。

你试图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);

或使用<>让它自动解决:

Triple<String, String, Function<String, String>> t1 = 
    Triple.of("str1", "str2", MyClass::minusOne);
Triple<String, String, Function<String, String>> t2 = 
    new ImmutableTriple<>("str1", "str2", MyClass::minusOne);

推荐阅读