{

Java8 - Learn java.util.Optional class with examples


java8 features - Java.util.Optional class with examples

Learn the Optional class in java8 with examples.

What is Optional Class in java

In Java Applications, Many Developers face NullPointerException during development. NullPointerException is a runtime exception that breaks the code.

Java8 introduced the Optional<T> class to avoid null value checking and NullPointerException.

Optional is a class defined in java.utilpackage since Java8 version.

It uses to check the values or object are present or not.

It avoids null checks and NullPointerExceptions.

The optional class is a container for holding values.

For example, The below function has a parameter with EmpId. It returns an employee object by making a call to the database with an employee Id.

Employee emp=findEmployeeById(1234) { };  
System.out.println("Salary "+emp.getSalary());  

Here EmployeeId is 1234. if an employee record does not exist in the database with id=1234, Then it returns a null object.

emp.getSalary() returns NullPointerException as emp object is null.

It is a common problem that developers overlook it and it causes the application to break.
With java8, the Optional class solves this. We will rewrite the same function as follows.

Optional<Employee> emp=findEmployeeById(1234) { };  
optional.ifPresent(emp -> {  
    System.out.println("Salary= " + emp.getSalary());     
});  

Optional has many utility methods to check object is present or not.
Here ifPresent() method checks for the null value. and used the lambda expression in it.

Here is an Optional Signature

public final class Optional<T> extends Object  

Optional Example
We will see the various usage of optional methods with examples.

How to create an Empty Optional Instance?

This method returns an empty object. No object exists in it. isPresent() return false and indicate the absence of value.

Optional<String> str = Optional.empty();  
System.out.println(str.isPresent()); // outputs false  

How to Create an optional non-empty instance?

Optional.of() method creates non null values. if null is passed, NullPointerException is thrown on this line and the Optional object is null.

import java.util.Optional;

public class OptionalClassExample {
    public static void main(String[] args) {
        Optional<String> str = Optional.of("One");
        System.out.println(str.isPresent()); // outputs true  
    }
}

Optional ofNullable() method

ofNullable() method accepts null and not null values.

import java.util.Optional;

public class OptionalClassExample {
    public static void main(String[] args) {
        Optional<Object> objOptional= Optional.ofNullable(null);
        System.out.println(objOptional.isPresent()); // outputs false  
        Optional<String> strOptional= Optional.ofNullable("One");
        System.out.println(strOptional.isPresent()); // outputs true 
    }
}

Optional isPresent() method usage

isPresent() method returns false - if optional object contains null values, else return true - if contain non null value

import java.util.Optional;

public class OptionalClassExample {
    public static void main(String[] args) {
        Optional<Object> objOptional= Optional.ofNullable(null);
        System.out.println(objOptional.isPresent()); // outputs false
        Optional<String> strOptional= Optional.ofNullable("One");
        System.out.println(strOptional.isPresent()); // outputs true  
    }
}

Optional ifPresent() method example

This method calls a specific consumer if the value is presented.

import java.util.Optional;

public class OptionalClassExample {
    public static void main(String[] args) {
        Optional<String> str = Optional.of("one");
        str.ifPresent(System.out::println);// This will be called  outputs one
        Optional<String> str1 = Optional.empty();
        str1.ifPresent(System.out::println); // This will not be called as no value preseneted in Optional class  

    }
}

Optional get() method example

get() method return value if presented in an optional container
else throws NoSuchElementException.
Please check value is presented or absent using isPresent() before using get() method.

import java.util.Optional;

public class OptionalClassExample {
    public static void main(String[] args) {
        Optional<String> emptyOption = Optional.empty();
        Optional<String> strOption = Optional.of("one");
        System.out.println( strOption.get());
        System.out.println( emptyOption.get());

    }
}

output:

one  
Exception in thread "main" java.util.NoSuchElementException: No value present  
 at java.base/java.util.Optional.get(Optional.java:148)  
 at org.cloudhadoop.defaultmethods.OptionalDemo.main(OptionalDemo.java:31)  

Optional orElse() method examples

orElse() method is useful to return default value if Optional object is empty
if the value is presented, return an optional value

import java.util.Optional;

public class OptionalClassExample {
    public static void main(String[] args) {
        Optional<String> str = Optional.of("one"); // Optional contains string value   
        System.out.println( str.orElse("defaultvalue")); // Outputs one  
        Optional<String> str1 = Optional.empty(); // Empty Optional object  
        System.out.println( str1.orElse("defaultvalue")); // defaultvalue is returned  

    }
}

Optional orElseGet() method example

orElseGet() method returns the value if the value is presented, else the supplier is being called and the value is returned it.

import java.util.Optional;

public class OptionalClassExample {
    public static void main(String[] args) {
        Optional<String> emptyOption = Optional.empty();
        Optional<String> strOption = Optional.of("one");
        System.out.println(emptyOption.orElseGet(() -> " optional null orElseGet"));
        System.out.println(strOption.orElseGet(() -> "Optional value orElseGet"));

    }
}

Output:

 optional null orElseGet  
one

Optional orElseThrow method example

orElseThrow method return value, if the value is presented else supplier is being called and throws an exception.

import java.util.Optional;

public class OptionalClassExample {
    public static void main(String[] args) {
        Optional<String> emptyOption = Optional.empty();
        Optional<String> strOption = Optional.of("one");
        try {
            System.out.println( emptyOption.orElseThrow(()->new Exception("Value is not present in Optional")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(strOption.orElseThrow(()->new Exception("Value is not present in Optional")));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Output:

java.lang.Exception: Value is not present in Optional  
 at org.cloudhadoop.defaultmethods.OptionalDemo.lambda$0(OptionalDemo.java:31)  
 at java.base/java.util.Optional.orElseThrow(Optional.java:397)  
 at org.cloudhadoop.defaultmethods.OptionalDemo.main(OptionalDemo.java:31)  
one  

Optional filter() method example

This method filter is used to filter the list of records.

if the value is presented and matches the given predicate. returning Optional Object
else returning the empty optional object.

import java.util.Optional;

public class OptionalClassExample {
    public static void main(String[] args) {
        Optional<String> strOptional = Optional.of("one two three");
        Optional<String> optionPredicate = strOptional.filter(s -> s.contains("one"));
        optionPredicate.ifPresent(System.out::println);
    }
}

Output:

one two three 

Optional map() method example

if the value is presented. and do the mapping to Function.
else returning empty optional object.

import java.util.Optional;

public class OptionalClassExample {
    public static void main(String[] args) {
        Optional<String> strOptional = Optional.of("ONETWOTHREE");
        Optional<String> srOptional1 = strOptional.map(String::toLowerCase);
        srOptional1.ifPresent(System.out::println);
    }
}

Output:

onetwothree  

Optional flatMap() method with example

flatMap() is similar to map() in functional programming.

if the value is presented. and do the specified optional mapping to Function.
else returning empty optional object.

Here is an java flatMap example

import java.util.Optional;

public class OptionalClassExample {
    public static void main(String[] args) {
        Optional strOptional = Optional.of("ONETWOTHREE");
        Optional strOptional1 = strOptional.flatMap(str -> Optional.of(str + " - appendthis"));
        strOptional1.ifPresent(System.out::println);
    }
}

Output:

ONETWOTHREE - appendthis  

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.