Home core java Java Optional class with examples

Java Optional class with examples

1. What is java Optional?

Java Optional class provides a way to deal with null values. It is used to represent a value is present or not. Java 8 added a new class Optional available in java.util package.

NullpointerException is a common issue in java applications. To prevent this, we normally add frequent NULL checks in our code to check if a variable is not empty before we use it in our program. Optional provides a better approach to handle such situations. Let us explore this by construct with some use cases.

2. Create Java Optional Object

public class CreateOptionalObjectDemo {
	public static void main(String[] args) {

		/*
		 * Optional.empty() returns an empty Optional.
		 */
		Optional emptyOptional = Optional.empty();
		/*
		 * Optional.of("Peter") returns non empty Optional.
		 * If value is null, will get NPE
		 */
		Optional nonEmptyOptional = Optional.of("Peter");
		/*
		 * Optional.ofNullable("Peter") returns non empty Optional.
		 * If value is null, will get Optional.empty()
		 */
		Optional nonEmptyOrEmptyOptional1 = Optional.ofNullable("Peter");
		Optional nonEmptyOrEmptyOptional2 = Optional.ofNullable(null);
		
		System.out.println(emptyOptional);
		System.out.println(nonEmptyOptional);
		System.out.println(nonEmptyOrEmptyOptional1);
		System.out.println(nonEmptyOrEmptyOptional2);
	}
}
Optional.empty
Optional[Peter]
Optional[Peter]
Optional.empty

3. Java Optional class methods

Modifier and TypeMethod and Description
static  Optionalempty() – Returns an empty Optional instance.
Optional<T>filter(Predicate<? super T> predicate)– If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.
 OptionalflatMap(Function<? super T,Optional> mapper) – If a value is present, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an emptyOptional.
Tget()– If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.
voidifPresent(Consumer<? super T> consumer) – If a value is present, invoke the specified consumer with the value, otherwise do nothing.
booleanisPresent()– Return true if there is a value present, otherwise false.
 Optionalmap(Function<? super T,? extends U> mapper) – 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.
static  Optionalof(T value)– Returns an Optional with the specified present non-null value.
static  OptionalofNullable(T value) – Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
TorElse(T other)– Return the value if present, otherwise return other.
TorElseGet(Supplier<? extends T> other) – Return the value if present, otherwise invoke other and return the result of that invocation.
Throwable> TorElseThrow(Supplier<? extends X> exceptionSupplier) – Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.

3.1. Optional.empty

public class OptionalTest1 {
 
    public static void main(String[] args) {
        
        //empty() - returns a empty Optional
        /*---------------------------------------------------*/
        Optional<String> emptyOptional = Optional.empty();
        System.out.println(emptyOptional);//Optional.empty
        
    }
}

Output :

- Advertisement -
Optional.empty
Optional[Peter]
Optional.empty

3.2. Optional.of

public class OptionalOfDemo {
	public static void main(String[] args) {

		// of() - returns a non-empty Optional with value
		/*-------------------------------------------------------*/
		Optional nonEmptyOptional = Optional.of("Peter");
		System.out.println(nonEmptyOptional);// Optional[Peter]
		System.out.println(Optional.of(null)); //NPE
	}
}

Output :

Optional[Peter]
Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.Objects.requireNonNull(Objects.java:221)
	at java.base/java.util.Optional.<init>(Optional.java:107)
	at java.base/java.util.Optional.of(Optional.java:120)
	at JavaSeExamples/com.javabydeveloper.core8.optional.OptionalOfDemo.main(OptionalOfDemo.java:12)

3.3. Optional.ofNullable

public class OptionalOfNullableDemo {
	public static void main(String[] args) {

		/*
		 * ofNullable() - Returns an Optional describing the specified value, if
		 * non-null, otherwise returns an empty Optional.
		 */
		/*----------------------------------------------------------*/
		Optional nonEmptyOptional = Optional.ofNullable("Peter Milanovich");
		Optional emptyOptional = Optional.ofNullable(null);
		System.out.println(nonEmptyOptional);// Optional[Peter Milanovich]
		System.out.println(emptyOptional);// Optional.empty

	}
}

Output :

Optional[Peter Milanovich]
Optional.empty

3.4. Optional.isPresent

public class OptionalIsPresesntDemo {
	public static void main(String[] args) {

		//isPresent() - returns true if value Present otherwise false
        /*----------------------------------------------------------*/
        Optional nonEmptyOptional = Optional.of("Peter Milanovich");
        Optional emptyOptional = Optional.empty();
        
        System.out.println(emptyOptional.isPresent());//false
        System.out.println(nonEmptyOptional.isPresent());//true

	}
}

Output :

false
true

3.5. Optional.ifPresent

public class OptionalIfPresesntDemo {
	public static void main(String[] args) {

		Optional<String> nonEmptyOptional = Optional.of("Peter Milanovich");
        Optional<String> emptyOptional = Optional.empty();
        
        // ifPresent() - if value present invoke specified Consumer
        /*----------------------------------------------------------*/
        Consumer<String> consumer = s -> System.out.println(s);
        nonEmptyOptional.ifPresent(consumer);//Peter
        emptyOptional.ifPresent(consumer);//never invoke consumer

	}
}

Output :

Peter Milanovich

3.6. Optional.filter

public class OptionalFilterDemo {
	public static void main(String[] args) {

		Optional<String> nonEmptyOptional = Optional.of("Peter Milanovich");
        Optional<String> emptyOptional = Optional.empty();
        
        /* filter() - If a value is present, and value matches the given predicate, 
         return an Optional otherwise return an empty Optional. */
        /*----------------------------------------------------------*/
        Predicate<String> predicate = s -> s.contains("Milanovich");
        System.out.println(nonEmptyOptional.filter(predicate));//Optional[Peter Milanovich]
        System.out.println(nonEmptyOptional.filter(s -> s.equals("Peter")));//Optional.empty
        System.out.println(emptyOptional.filter(predicate));//Optional.empty
        System.out.println(nonEmptyOptional.filter(s -> s.startsWith("P")));//Optional[Peter Milanovich]

	}
}

Output :

Optional[Peter Milanovich]
Optional.empty
Optional.empty
Optional[Peter Milanovich]

3.7. Optional.map

public class OptionalMapDemo {
	public static void main(String[] args) {

		Optional<String> nonEmptyOptional = Optional.of("Peter Milanovich");
		Optional<String> emptyOptional = Optional.empty();

		/*
		 * map() - 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.
		 * Otherwise return an empty Optional.
		 */
		/*----------------------------------------------------------*/
		Function<String, String> function = s -> s.substring(0, 0).length() == 0 ? null : s;
		
		System.out.println(nonEmptyOptional.map(function));// Optional.empty
		System.out.println(nonEmptyOptional.map(String::toLowerCase));// Optional[peter milanovich]
		System.out.println(emptyOptional.map(function));// Optional.empty

	}
}

Output :

Optional.empty
Optional[peter milanovich]
Optional.empty

3.8. Optional.flatMap

public class OptionalFlatMapDemo {
	public static void main(String[] args) {

		/* 
		 * flatMap() - This method is similar to map(Function),
         * but the provided mapper is one whose result is already an Optional, and if invoked,
         * flatMap does not wrap it with an additional Optional.
         * */
        /*----------------------------------------------------------*/
        Optional<Optional> optionalContainer = Optional.of(Optional.of("Peter Milanovich"));
        Optional<Optional> emptyOptionalContainer = Optional.of(Optional.of("Peter Milanovich"));
        
        Function<String, String> function = s -> s.substring(0, 0).length() == 0 ? null : s;
        Function<String, String> function2 = s -> s.substring(0, 5);
        
        System.out.println(optionalContainer.map(optional -> optional.map(function2)));//Optional[Optional[Peter]]
        System.out.println(optionalContainer.flatMap(optional -> optional.map(function2)));//Optional[Peter]
        System.out.println(emptyOptionalContainer.flatMap(optional -> optional.map(function)));//Optional.empty

	}
}

Output :

Optional[Optional[Peter]]
Optional[Peter]
Optional.empty

3.9. Optional.orElse

public class OptionalOrElseDemo {
	public static void main(String[] args) {

		Optional<String> nonEmptyOptional = Optional.of("Peter Milanovich");
        Optional<String> emptyOptional = Optional.empty();
        
        // orElse() - Return the value if present, otherwise return other.
        /*----------------------------------------------------------*/
        System.out.println(nonEmptyOptional.orElse("Gerhard Gogoush"));//Peter Milanovich
        System.out.println(emptyOptional.orElse("Gerhard Gogoush"));//Gerhard Gogoush

	}
}

Output :

Peter Milanovich
Gerhard Gogoush

3.10.  Optional.orElseGet

public class OptionalOrElseGetDemo {
	public static void main(String[] args) {

		Optional<String> nonEmptyOptional = Optional.of("Peter Milanovich");
        Optional<String> emptyOptional = Optional.empty();
        
        /* orElseGet - Return the value if present, otherwise invoke other 
        and return the result of that invocation.*/
        /*----------------------------------------------------------*/
        Supplier<String> supplier = () -> "Gerhard Gogoush";
        
        System.out.println(nonEmptyOptional.orElseGet(supplier));//Peter Milanovich
        System.out.println(emptyOptional.orElseGet(supplier));//Gerhard Gogoush
	}
}

Output :

Peter Milanovich
Gerhard Gogoush

3.11. Optional.orElseThrow

public class OptionalOrElseThrowDemo {
	public static void main(String[] args) {

		Optional<String> nonEmptyOptional = Optional.of("Peter Milanovich");
        Optional<String> emptyOptional = Optional.empty();
        
        // orElseThrow() - Return the contained value, if present, otherwise 
        //throw an exception to be created by the provided supplier.
        /*----------------------------------------------------------*/
        System.out.println(nonEmptyOptional.orElseThrow(NullPointerException::new));//Peter Milanovich
        System.out.println(emptyOptional.orElseThrow(NullPointerException::new));//NullPointerException
	}
}

Output :

Peter Milanovich
Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.Optional.orElseThrow(Optional.java:408)
	at JavaSeExamples/com.javabydeveloper.core8.optional.OptionalOrElseThrowDemo.main(OptionalOrElseThrowDemo.java:15)

Reference

  1. Java documentation

- Advertisement -
Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Also founder of javabydeveloper.com. Follow him on LinkedIn or Twitter or Facebook

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay in Touch

Categories

Related Articles