Java Tutorials
Java Optional
Java Optional Class is a reference Type, Assigning a null value to Optional object, is an error.
Optional Class located in java.util package
Other Optional Classes You can not create a Optional
of(T)
ofNullable(T)
Optional<String> opt = Optional.empty(); String str = null; Optional<String> opt = Optiona.of(str); //throws an Exception better to deal above case using ofNullable method. Optional<String> opt = Optional.ofNullable(str);
Accessing a value from Optional Object first needs to check is value present using isPresent() method ,true means value exists then call get method
. Directly accessing a value using get method may throw an Exception.String str = "Text Message"; Optional<String> opt = Optional.ofNullable(str); //Alwyas Check if non-null value present in Optional Object. using isPresent method //then call get method if( opt.isPresent() ) System.out.println( opt.get() );
getMobileNo method returns Optional<String> object, in function body, checks given string has 10-digit mobile number, if exists
returns
mobile number as a string,passed to Optional.of(no) method
elsenull value using Optional.ofNullable(null)
Optional<String> getMobileNo(String no){ if( no.matches( "Phone:(\\d){10}") ) return Optional.of(no.replace("Phone:","")); else return Optional.ofNullable(null); }
mobile number passed to getMobileno() method, returns Optional object.
In order to access value from Optional object, if value present using isPresent then call get method, otherwise get method throws NoSuchElementException Exception.
Note: Used ternery Operator to access a value.
String no = "Phone:8767896666"; Optional<String> optional = getMobileNo(no); String phone = (optional.isPresent())?optional.get():"NOT FOUND"; System.out.println(phone);
In above code used terneray operator to get a value , if value not found returns "NOT FOUND". terneray operator can be replaced with orElse method as shown below
System.out.println( optional.orElse("NOT FOUND") );
ifPresent method ,if value presents invokes specified consumer interface, returns nothing. Note: Consumer interfaces takes input values, processes it, returns nothing.
ifPresent syntax:ifPresent(Consumer<? super T> consumer)
Consumer interface can be used to format the given Phone number.
opt.ifPresent( (s)->System.out.println(s.substring(0,3)+"-"+s.substring(3,6)+"-"+s.substring(6,10)))Consumer interface can be implemented using Method Reference. We have a class called Formatter, which has method called Format,accpets input param String Class Formatter876-789-6666
class Formatter { static void format(String str){ System.out.println( str.substring(0,3)+"-"+str.substring(3,6)+"-"+str.substring(6,10)); } }Calling ifPresent method using Method reference
optional.ifPresent( Formatter::format );876-789-6666
ADS