【问题标题】:Java streams to compare between objects and return that object?Java 流在对象之间进行比较并返回该对象?
【发布时间】:2018-07-14 13:05:26
【问题描述】:

我有一个类对象的ArrayList,如下所示:

ArrayList<Score> scoreboard = new ArrayList<>();

Score 类有一个字段points

class Score {
    private int points; 
    //constructor and methods
}

我将如何使用 Java 流来比较每个 Score 对象中的 points 并返回具有最高/最低值的对象?

我尝试了类似的方法,但没有成功:

scoreboard
    .stream()
    .max(Comparator.comparing(Score::getPoints)
    .get()
    .forEach(System::println);

【问题讨论】:

  • 定义不工作

标签: java java-8 java-stream comparator


【解决方案1】:

仔细看看你尝试了什么:

scoreboard.stream().max(Comparator.comparing(Score::getPoints).get().forEach(System::println);

在这里,您正在尝试创建Comparator

Comparator.comparing(Score::getPoints).get().forEach(System::println)

你还没有平衡括号;而你正在使用一种不存在的方法,System::println

将括号放在正确的位置:

Score maxScore = scoreboard.stream().max(Comparator.comparingInt(Score::getPoints)).get();
                                                                        // Extra  ^

然后打印出来:

System.out.println(maxScore);

或者,如果您不确定流是否为非空:

Optional<Score> opt = scoreboard.stream().max(...);
opt.ifPresent(System.out::println);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多