Car*_*ein 2 java comparator java-8 java-stream
我有ArrayList一个类对象,如下所示:
ArrayList<Score> scoreboard = new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)
该Score班有一个字段points:
class Score {
private int points;
//constructor and methods
}
Run Code Online (Sandbox Code Playgroud)
我将如何使用Java流来比较points每个Score对象并返回具有最高/最低值的对象?
我试过这样的东西,但它不起作用:
scoreboard
.stream()
.max(Comparator.comparing(Score::getPoints)
.get()
.forEach(System::println);
Run Code Online (Sandbox Code Playgroud)
仔细看看你尝试过的东西:
scoreboard.stream().max(Comparator.comparing(Score::getPoints).get().forEach(System::println);
Run Code Online (Sandbox Code Playgroud)
在这里,您正在尝试创建Comparator:
Comparator.comparing(Score::getPoints).get().forEach(System::println)
Run Code Online (Sandbox Code Playgroud)
你没有平衡括号; 而你正在使用一种不存在的方法System::println.
把括号放在正确的位置:
Score maxScore = scoreboard.stream().max(Comparator.comparingInt(Score::getPoints)).get();
// Extra ^
Run Code Online (Sandbox Code Playgroud)
然后打印出来:
System.out.println(maxScore);
Run Code Online (Sandbox Code Playgroud)
或者,如果您不确定该流是非空的:
Optional<Score> opt = scoreboard.stream().max(...);
opt.ifPresent(System.out::println);
Run Code Online (Sandbox Code Playgroud)