SEARCH BY

All

  • All
  • Java8
  • Spring

Optional interface in java

Post a Comment
We will see the details about Optional interface in java which introduced from java8.
Dealing with nullpointer exception is big tricky part in java application development. To overcome nullpointer  hurdles we can use Optional interface which holds value or empty.
package java8examples; 

import java.util.Optional;
import java.util.function.Predicate;

public class OptionalExamples {

 
 public static void main(String args[]) {
  
  
  Optional<String> names= Optional.of("Ganguly");
  
  Predicate<String> nameStartsWith= n -> n.toLowerCase().startsWith("g");
  
  
  
  if(names.filter(nameStartsWith).isPresent()) {
   
   
   System.out.println(names.get());
  } else {
   
   
   System.out.print("No Name");
  }
  
  
  
 }
}



References: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Optional.html


jaya
I love software designing, coding, writing and teaching...

Share this article

Related Posts

Post a Comment

Place your code in <em> </em> tags to send in comments | Do not add hyper links in commnet

Close

Subscribe our newsletter for the latest articles directly into your email inbox