sdicola
sdicola

Reputation: 962

Java 8 Calculate minimum value

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?

Upvotes: 2

Views: 635

Answers (3)

holi-java
holi-java

Reputation: 30686

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);
}

Upvotes: 4

stholzm
stholzm

Reputation: 3455

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.

Upvotes: 3

shizhz
shizhz

Reputation: 12501

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)

Upvotes: 0

Related Questions