In this tutorial, we will take a look into how to use the Optional class to avoid null checks and NullPointerException.
Well, the NullPointerException is one of the well-known exceptions that frequently occurs in day-to-day project work right and NullPointerException is like a close friend to the java programmer because whenever we write a program or whenever we work on java project then this null pointer exception will frequently occur all right.
Video
Java 8 has introduced a new Optional utility class in java.util package. This class can help in avoiding null checks and NullPointerException exceptions.
You can view Optional as a single-value container that either contains a value or doesn't (it is then said to be "empty").
Let's understand some of the frequently or commonly used Java 8 Optional Class methods with examples.
Creating Optional Objects
There are several ways of creating Optional objects.empty() Method
To create an empty Optional object, we simply need to use its empty() static method: Optional<Object> emptyOptional = Optional.empty();
of() Method
The of() static method returns an Optional with the specified present non-null value.
Optional<String> emailOptional = Optional.of("ramesh@gmail.com");
ofNullable() Method
The ofNullable() static method returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional. Optional<String> stringOptional = Optional.ofNullable("ramesh@gmail.com");
Here is the complete example with output:
import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
String email = "ramesh@gmail.com";
// of, empty, ofNullable
Optional<Object> emptyOptional = Optional.empty();
System.out.println(emptyOptional);
Optional<String> emailOptional = Optional.of(email);
System.out.println(emailOptional);
Optional<String> stringOptional = Optional.ofNullable(email);
System.out.println(stringOptional);
}
}
Output:
Optional.empty
Optional[ramesh@gmail.com]
Optional[ramesh@gmail.com]
Get Value from Optional
get() Method
The get() method returns a value if it is present in this Optional otherwise throws NoSuchElementException.package com.java.lambda.optional;
import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
String email = "ramesh@gmail.com";
Optional<String> stringOptional = Optional.ofNullable(email);
String value = stringOptional.get();
System.out.println(value);
}
}
ramesh@gmail.com
Checking Value Presence
isPresent() Method
The isPresent() method returns true if there is a value present, otherwise false.import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
String email = "ramesh@gmail.com";
Optional<String> stringOptional = Optional.ofNullable(email);
if(stringOptional.isPresent()){
System.out.println(stringOptional.get());
}else{
System.out.println("no value present");
}
}
}
ramesh@gmail.com
Retrieve Default Value
orElse() Method
The orElse() method returns the value if present, otherwise return other (default value).import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
String email = null;
Optional<String> stringOptional = Optional.ofNullable(email);
String defaultOptional = stringOptional.orElse("default@gmail.com");
System.out.println(defaultOptional);
}
}
default@gmail.com
import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
String email = "ramesh@gmail.com";
Optional<String> stringOptional = Optional.ofNullable(email);
String defaultOptional = stringOptional.orElse("default@gmail.com");
System.out.println(defaultOptional);
}
}
ramesh@gmail.com
orElseGet() Method
The orElseGet() method returns the value if present, otherwise invoke other and return the result of that invocation.import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
String email = null;
Optional<String> stringOptional = Optional.ofNullable(email);
String defaultOptional2 = stringOptional.orElseGet(() -> "default@gmail.com");
System.out.println(defaultOptional2);
}
}
default@gmail.com
import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
String email = "ramesh@gmail.com";
Optional<String> stringOptional = Optional.ofNullable(email);
String defaultOptional2 = stringOptional.orElseGet(() -> "default@gmail.com");
System.out.println(defaultOptional2);
}
}
ramesh@gmail.com
Handling Exceptions with Optional
orElseThrow() Method
package com.java.lambda.optional;
import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
String email = null;
Optional<String> stringOptional = Optional.ofNullable(email);
String optionalObject = stringOptional.orElseThrow(() -> new IllegalArgumentException("Email is not exist"));
System.out.println(optionalObject);
}
}
Output:
Exception in thread "main" java.lang.IllegalArgumentException: Email is not exist
at com.java.lambda.optional.OptionalDemo.lambda$main$0(OptionalDemo.java:10)
at java.base/java.util.Optional.orElseThrow(Optional.java:403)
at com.java.lambda.optional.OptionalDemo.main(OptionalDemo.java:10)
import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
String email = "ramesh@gmail.com";
Optional<String> stringOptional = Optional.ofNullable(email);
String optionalObject = stringOptional.orElseThrow(() -> new IllegalArgumentException("Email is not exist"));
System.out.println(optionalObject);
}
}
Output:
ramesh@gmail.com
Optional filter() and map() Methods
filter() Method
If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
// without Optional
String result = "abc";
if(result != null && result.contains("abc")){
System.out.println(result);
}
// with Optional
Optional<String> optionalStr = Optional.of(result);
optionalStr.filter(res -> res.contains("abc"))
.ifPresent((res) -> System.out.println(res));
}
}
Output:
abc
abc
map() Method
If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result.import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
String result = " abc ";
if(result != null && result.contains("abc")){
System.out.println(result);
}
Optional<String> optionalStr = Optional.of(result);
optionalStr.filter(res -> res.contains("abc"))
.map(String::trim)
.ifPresent((res) -> System.out.println(res));
}
}
Output:
Comments
Post a Comment
Leave Comment