2

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);
1
  • 7
    define not working. Commented Feb 4, 2018 at 15:22

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.