【发布时间】:2020-01-29 16:09:55
【问题描述】:
我知道这将是今天 Stackoverflow 上的蹩脚问题......但我仍然想在 java 中找到以下 sn-p 的功能
理想情况下,我们应该将'Scoreable scoreable' 对象传递给collection.add,但是这个()->5 是什么?以及它如何将 int 值转换为 Scoreable 类型
public class ScoreCollectionTest {
public void addTwoNumbersForMean() {
ScoreCollection collection = new ScoreCollection();
collection.add(()->5);
collection.add(()->7);
}
}
public class ScoreCollection {
private List<Scoreable> scores = new ArrayList<>();
public void add(Scoreable scoreable) {
scores.add(scoreable);
}
public int arithmeticMean() {
int total = scores.stream().mapToInt(Scoreable::getScore).sum();
return total / scores.size();
}
}
这里是Scoreable接口
public interface Scoreable {
int getScore();
}
【问题讨论】:
-
看一下
Scoreable的定义,应该很明显了。 -
@Smutje, ``` public interface Scoreable { int getScore(); } ``` ()-> 表示从 Scorable 接口返回 int 值,因为它只有一个方法?
-
如果您了解 lambdas,可能会更容易理解,并将其阅读为
() -> 5(即带有空格)。相关:stackoverflow.com/questions/25192108/…