Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove "Optional[…]" from a Console OutPrint in Java / IntelliJ

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading