简体   繁体   中英

Java streams to compare between objects and return that object?

I have an ArrayList of a class object like below:

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

The Score class has a field points :

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

How would i go about using Java streams to compare the points in each of this Score object and return the object with the highest/lowest value?

I tried something like this but it did not work:

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

Look carefully at what you tried:

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

Here, you're trying to create a Comparator :

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

and you've not balanced the parentheses; and you're using a non-existent method, System::println .

Put the parentheses in the right place:

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

Then print it:

System.out.println(maxScore);

Or, if you're not sure that the stream is non-empty:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM