-1

I'm studying programming and I'm working on streams in Java. I wrote a methode which should return the tallest Human-Object out of a doctors-patient List.

public static void tallestPatient(List<Human> patients) throws NullPointerException {
    try {
        System.out.println("Tallest patient: ");
        System.out.print(patients.stream().max(Comparator.comparingInt(Human::getHeight)));
        System.out.println();
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

The method itself works. I just noticed, that there's this "Optional[...]" Tag ont the console whenever I try to print the toString() Method of the choosen Object (tallest Human) out.

Console-Output:

Tallest patient: Optional[Peter is a man with private insurance from USA and is about 220cm high.]

IDE told me, that's because the element could be zero if it's a empty list. tried to cancel that out, by considering NullPointerExceptions as well as an if and else condition, which also didn't solve the problem, why is stayed with the exception variant.

Does anyone have an idea, what I could fix?

Greetings Justin

1 Answers1

2

The aggregate function Stream::max returns an Optional, and the toString-implementation of Optional produces the String we observe.

We can prevent this by unwrapping the Optional. One possible way would be to call Optional::orElse:

System.out.print(patients.stream()
  .max(Comparator.comparingInt(Human::getHeight))
  .orElse(null));

Another possibility would be to only print the value if a value is present through Optional::ifPresent:

patients.stream()
  .max(Comparator.comparingInt(Human::getHeight))
  .ifPresent(System.out::println)

A remark on the code: The decision to catch the NullPointerException is at least questionable. I would advice to enforce non-nullity explicitly.

Turing85
  • 18,217
  • 7
  • 33
  • 58