Java 8 – Optional class

Java 8 contains a new class called ‘Optional’ in the utils package which is used to represent a value is present or not.

This class is used to avoid the Null pointer exception. So we don’t need to do any null check in our code if we use Optional object along with our object.

Refer the below example to know how we can use the Optional class.


import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class OptionalMain {

    public static void main(String[] args) {

        OptionalMain optionalMain = new OptionalMain();
        optionalMain.testBasic();
        optionalMain.testFilter();
        optionalMain.testMap();
    }

    private void testBasic() {

        // Create the Optional object with a string object. Note the string is null.
        //This will create Optional.empty as the value is null
        Optional stringOptional = Optional.ofNullable(null);
        System.out.println("stringOptional:" + stringOptional);
        try {
            //If you pass null value to of method, then it will throw Null pointer exception
            System.out.println("ofNullable on Non-Empty Optional: " + Optional.of(null));
        }
        catch (NullPointerException npx) {
            npx.printStackTrace();
        }

        // Check whether the value is present in the Optional object
        System.out.println("stringOptional value is present: " + stringOptional.isPresent());

        // Get the value from the Optional object. If its null, then return the default value
        // passed to the orElse method
        System.out.println("stringOptional value " + stringOptional.orElse("EMPTY"));

        // Create the Optional object with a string object.
        Optional nameOptional = Optional.ofNullable("name");
        System.out.println("nameOptional name is present:" + nameOptional.isPresent());
        nameOptional.ifPresent(name -> System.out.println("Name is available"));

        try {
            // Get the value from the Optional object. If its null, then throw an exception
            System.out.println("stringOptional value " + stringOptional.orElseThrow(RuntimeException::new));
        }
        catch (RuntimeException ex) {
            ex.printStackTrace();
        }
    }

    private void testFilter() {
        Optional nameOptional = Optional.of("john");
        System.out.println("Filter Operation:" + nameOptional.filter(name -> name.equals("john")));
        Optional numOptional = Optional.of(100);
        System.out.println(numOptional.filter(value -> value > 10));
        System.out.println(numOptional.filter(value -> value > 100));
    }

    private void testMap() {

        List fruits = Arrays.asList("apple", "orange", "banana");
        Optional<List> fruitsOptional = Optional.ofNullable(fruits);
        System.out.println("Fruits" + fruitsOptional.get());
        System.out.println("Mapping the Fruits " + fruitsOptional.get().stream().map(String::toUpperCase)
                .collect(Collectors.toList()));

    }
}

Output:


stringOptional:Optional.empty
stringOptional value is present: false
stringOptional value EMPTY
nameOptional name is present:true
java.lang.NullPointerException
	at java.util.Objects.requireNonNull(Objects.java:203)
	at java.util.Optional.(Optional.java:96)
	at java.util.Optional.of(Optional.java:108)	
Name is available
java.lang.RuntimeException
	at java.util.Optional.orElseThrow(Optional.java:290)
Filter Operation:Optional[john]
Optional[100]
Optional.empty
Fruits[apple, orange, banana]
Mapping the Fruits [APPLE, ORANGE, BANANA]


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s