传递不同的方法作为参数在Java中8
问题描述:
我一直在寻找到lambda表达式,以及如何传递方法,如在Java 8争论,但我不知道它可能在我的情况:传递不同的方法作为参数在Java中8
我有多个类具有类似的方法,但方法名称在某些类中是不同的。每个方法都将一个Long作为表示ID的参数。 所以,我试图让:
void setScore(List<Long> nodes, method){
for (Long id : nodes)
System.out.println(method(id));
}
}
这是我想传递方法的两个例子,但我有:
Double DegreeScorer<Long>.getVertexScore(Long id)
Double BetweennessCentrality<Long, Long>.getVertexRankScore(Long 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);
答
如果所有方法都返回一个Double
使用java.util.Function<Long,Double>
:
void setScore(List<Long> nodes, Function<Long,Double> fn) {
for (Long id : nodes)
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));
}
}
'LongToDoubleFunction'如何? – Tunaki
LongFunction? R是返回类型。 –
gmaslowski
你如何将函数作为参数传递?我的类存储算法的结果,所以我想先调用ranker.evaluate(),然后传递ranker.getVertexScore(Long id)。调用setScore时使用什么语法? setScore(nodes,ranker.getVertexScore)给了我一个错误 – user1171426