在Java8中作为参数传递不同的方法
我一直在研究lambda表达式以及如何在java 8中将方法作为参数传递,但我不确定在我的例子中是否可能: 我有多个具有类似方法的类,但某些类中的方法名称不同。每个方法都需要很长的时间作为表示ID的参数。 所以,我想说:在Java8中作为参数传递不同的方法,java,function,lambda,java-8,arguments,Java,Function,Lambda,Java 8,Arguments,我一直在研究lambda表达式以及如何在java 8中将方法作为参数传递,但我不确定在我的例子中是否可能: 我有多个具有类似方法的类,但某些类中的方法名称不同。每个方法都需要很长的时间作为表示ID的参数。 所以,我想说: void setScore(List<Long> nodes, method){ for (Long id : nodes) System.out.println( method(id) ); } } void setScore(列
void setScore(List<Long> nodes, method){
for (Long id : nodes)
System.out.println( method(id) );
}
}
void setScore(列出节点、方法){
用于(长id:节点)
System.out.println(方法(id));
}
}
这是我想通过的两个方法示例,但我有:
Double DegreeScorer<Long>.getVertexScore(Long id)
Double BetweennessCentrality<Long, Long>.getVertexRankScore(Long id)
Double DegreeScorer.getVertexScore(长id)
双中间值中心。getVertexRankScore(长id)
我以为我已经找到了使用LongConsumer接口的解决方案,但LongConsumer不返回任何值,因此我无法存储结果
任何帮助都将不胜感激
更新:
我的结局是:
<T> void setScore(List<Long> nodes, LongFunction<T> getScore){
for (Long id : nodes)
System.out.println(getScore.apply(id));
}
}
setScore(nodes, ranker::setVertexScore);
void setScore(列出节点,长函数getScore){
用于(长id:节点)
System.out.println(getScore.apply(id));
}
}
setScore(节点,ranker::setVertexScore);
如果所有方法都返回一个Double
则使用java.util.Function
:
void setScore(列出节点,函数fn){
用于(长id:节点)
System.out.println(fn.apply(id));
}
}
如果有不同的返回类型,请添加泛型类型参数
<T> void setScore(List<Long> nodes, Function<Long,T> fn) {
for (Long id : nodes)
System.out.println(fn.apply(id));
}
}
void setScore(列出节点,函数fn){
用于(长id:节点)
System.out.println(fn.apply(id));
}
}
关于LongtodoupleFunction
的情况如何?关于LongtoopleFunction的情况如何?R是返回类型。如何将函数作为参数传递?我的类存储算法的结果,所以我想先调用ranker.evaluate(),然后传递ranker.getVertexScore(长id)。调用setScore时使用什么语法?setScore(nodes,ranker.getVertexScore)给我一个错误你可以(可能)用setScore(nodes,l->ranker.getVertexScore(l))
或setScore(nodes,ranker::getVertexScore)
。请阅读lambda教程了解更多信息类型参数
已过时。该方法可以接受一个函数
,结果没有任何差异。@霍尔格你说得对,示例并不依赖于它。但通常情况下,您可能需要类型参数,而不仅仅是?
<T> void setScore(List<Long> nodes, Function<Long,T> fn) {
for (Long id : nodes)
System.out.println(fn.apply(id));
}
}