2

I am practicing with Java 8. I don't understand why this method always return 0, or better the identity value:

public static Integer getMinAge(List<Person> peopleList) {
    return peopleList.stream().mapToInt(Person::getAge).reduce(0, Integer::min);
}

Surprisingly, the Integer::max method returns the correct value. What am I doing wrong here?

4
  • 6
    Because you provided the identity value of zero, you apply the function Integer.min, and you don't have any negative ages, logically, so zero is always the lowest value?! Try reduce(Integer.MAX_VALUE, Integer::min) Commented Mar 26, 2017 at 12:41
  • You are absolutely right! Thanks a lot! Commented Mar 26, 2017 at 12:43
  • 3
    You could use .reduce(Integer::min) or even .min() instead, but those methods return an OptionalInt - because without the provided identity value, there may be no result (if the stream is empty!) Commented Mar 26, 2017 at 12:44
  • Even better! Thanks! Commented Mar 26, 2017 at 12:45

3 Answers 3

4

because age > 0 and identity == 0 then Integer.min(identity,age) always return 0.

use IntStream.reduce(IntBinaryOperator)

public static Integer getMinAge(List<Person> peopleList) {
  return peopleList.stream().mapToInt(Person::getAge)
            .reduce(Integer::min).orElse(0);
}

use IntStream.min()

public static Integer getMinAge(List<Person> peopleList) {
  return peopleList.stream().mapToInt(Person::getAge)
           .min().orElse(0);
}
Sign up to request clarification or add additional context in comments.

Comments

3

The question has already been answered in the comments, but I do not think that the minimum age of zero people should be 0, or Integer.MAX_INT. I prefer:

public static Integer getMinAge(List<Person> peopleList) {
    return peopleList.stream().mapToInt(Person::getAge).min().getAsInt();
}

min() is the most concise solution and it forces you to think about the corner case of an empty stream. In your case, I'd treat it as a programmer error and throw an exception.

Comments

0

Because you called reduce(0, Integer::min), 0 itself is the smallest number among people's age list. You can refer to java doc of IntStream.recude for more details. If you need to find the youngest people, you need call it like reduce(Integer.MAX_VALUE, Integer::min)

1 Comment

Careful; if the stream happens to be empty, it will return Integer.MAX_VALUE, which is kind of unexpected.

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.