javajava-8method-reference

Multiple print statements without null checks using Optional


I am trying to convert the below null check of legacy java 7 code to modern java using Streams and Optional.

if (person != null) {
  System.out.println(person.getName());
  System.out.println(person.getAge());
}

I have tried the below snippet for the same but I believe there must be a better way instead of repeating the same code in multiple lines.

Optional.ofNullable(person).map(Person::getName).ifPresent(System.out::println);
Optional.ofNullable(person).map(Person::getAge).ifPresent(System.out::println);

Can anybody suggest how can I print both the values using a single statement using the Java 8 stream pipeline.


Solution

  • You can have both print statements in ifPresent using lambda expression

    Optional.ofNullable(person)
            .ifPresent(details-> {
    
              System.out.println(details.getName());
              System.out.println(details.getAge());
    
            });