java - 如何将方法引用传递给 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));
感谢您的帮助和安慰 - 否则我不会找到它
解决方案
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);
推荐阅读
- reactjs - 如何在 React 中迭代类变量?
- scala - 使用scala或spark sql从spark中第二个表中不存在的第一个表中选择值
- html - 如何将图像定位在作为 flex 子项的文本的右侧
- security - JWE 和密钥管理模式
- express - 获取`Cannot GET /todos`
- c++ - 将在 lambda 捕获站点构建的 unique_ptr 移动到向量中失败
- mysql - 无法启动 zabbix-server-mysql 的 docker 映像:'无法使用数据库“zabbix”:其“用户”表为空(这是 Zabbix 代理数据库吗?)'
- javascript - Javascript 日期到字符串(格式 hh:mm)
- reactjs - 不是来自 webpack 的内容是从反应中提供的
- python - 为什么我的函数在运行一次后停止从文件中读取?