Java8 is not so new now. Everybody is well aware and probably using it in one or the other project. Certainly, Java8 is a big leap for Java since it makes Java functional.
(though its procedural internally). Anyway, it successfully got interested in the IT industry.

In this blog, I am going to talk about one of the vital features of Java8 i.e. Optional. Optional, as the name suggests gives an option to use/operate on the value. Let’s dive deep into the world of Optional.
Optional is basically a container object which may or may not have the Not-Null value. It is used for representing a value. The main use of the Optional class is to avoid “NullPointerException“.

Optional is part of the java.util package, so we need to create this import:

import java.util.Optional;

How to create Optional Object?

There are several ways of creating Optional objects.
Empty Optional Object :

@Test
public void emptyOptional_thenCorrect() {
Optional  empty = Optional.empty();
assertFalse(empty.isPresent());
}

Optional Object with Static value :

@Test
public void notNullOptional_thenCorrect() {
String name = "StaticValue";
Optional value = Optional.of(name);
assertEquals("Optional[StaticValue]", value.toString());}

Advantages of Optional in Java 8 :

• There is no need for Null checks.
• No more chances for NullPointerException at runtime.
• No boilerplate in the code (neat and clean code).

Let’s go through the methods used with the optional :
empty(): It returns an empty optional instance.
Syntax : public static Optional empty()

public void emptyOptional(){
Optional empty = Optional.empty();
//Optional.empty() will create an optional empty instance.
....
}

Of(): It returns an optional instance with non-null value.
Syntax : public static Optional of(T value)

public void valuedOptional(){
String data = “Some Data”;
Optional value = Optional.of(data);
//It will create an optional instance with data as the value.
. . . .
}

ofNullable(): If the value is present in the optional then return the not-null value, otherwise returns an empty optional instance.
Syntax : public static Optional ofNullable(T value)

public void ofNullableOptional() {
String data = “Not Null Data”;
Optional value = Optional.ofNullable(data);
// It will create an optional instance with data as the value. If the data is null then it will return an empty optional instance.
. . . .
}

get(): If the value is present in the optional then return the not-null value, otherwise throws NoSuchElementException.
NOTE: We should not use get method. As it deals only with one side of the value.
Syntax : public T get()

public void getOptional() {
String data = “Some value”;
Optional value = Optional.ofNullable(data);
value.get() ;
//It will create an optional instance with data as the value. If the data is null then it will throws NoSuchElementException.
. . . .
}

isPresent(): It returns a boolean value. (True or False) If the value is present then true otherwise false.
Syntax : public boolean isPresent()

Optional data = Optional.of("Hello");
Optional emptyData = Optional.empty();
public Optional getData() {
if(data.isPresent()){ // tell the value is avilable or not
return data ;
}
return data ;
}

ifPresent(): If the value is present, invoke the customer with the provided value otherwise do nothing.
Syntax : public void ifPresent(Customer consumer)

Optional data = Optional.of("Hello");
Optional emptyData = Optional.empty();
public Optional getDataIfPresent() {
data.ifPresent(data -> System.out.println("found data"));
emptyData.ifPresent(data -> System.out.println("no data found"));
return data ;
}

filter(): If a value is present, and the value matches the given predicate, return an optional describing the value, otherwise return an empty optional.
Syntax : public Optional filter(Predicate predicate)

Optional data = Optional.of("Hello");
Optional emptyData = Optional.empty();
System.out.println(data.filter(g -> g.equals("hello"))); //Optional.empty
System.out.println(data.filter(g -> g.equalsIgnoreCase("Hello"))); //Optional[Hello]
System.out.println(emptyData.filter(g -> g.equalsIgnoreCase("Hello"))); //Optional.empty

map(): If the value is present then map the mapping provided to it, otherwise return the empty Optional.
Syntax: public Optional map(Function mapper)

public class Demo {
    class Person {
        private String name = "Hello To Optional";
        public Optional getName() {
            return Optional.ofNullable(name);
        }
    }
	public void optionalMethodDemo() {
        Person person = new Person();
        Optional personOptional = Optional.of(person);
	Optional
<optional> wrapper = personOptional.map(Person::getName);
        Optional nameOptional = wrapper.orElseThrow(IllegalArgumentException::new);
        String name1 = nameOptional.orElse("");
	System.out.println("name1 :: " + name1);
	}
	public static void main(String []args){
        Demo demo = new Demo();
        demo.optionalMethodDemo();
	}
}

flatMap(): It is similar to map, the only difference is that flatMap does not wrap it with an additional Optional.
Syntax : public Optional flatMap(Function<? super T,Optional>mapper)

public class Demo {
    class Person {
        private String name = "Hello To Optional";
        public Optional getName() {
            return Optional.ofNullable(name);
        }
    }
    public void optionalMethodDemo() {
        Person person = new Person();
        Optional personOptional = Optional.of(person);
	Optional dataWithNull = Optional.ofNullable(null);
 	String name = personOptional.flatMap(Person::getName).orElse("");
	System.out.println("name :: " + name);
	}
	public static void main(String []args){
        Demo demo = new Demo();
        demo.optionalMethodDemo();
	}
}

orElse(): Return the value if the value is present , otherwise return the default value.
Syntax : public T orElse(T other)

Optional data = Optional.of("Hello");
Optional emptyData = Optional.empty();
System.out.println(data.orElse("")); //Hello
System.out.println(emptyData.orElse("")); //

orElseGet(): Return the value if the value is present, otherwise invoke other and return the result of that invocation.
Syntax: public T orElseGet(Supplier other)

Optional data = Optional.of("Hello");
Optional emptyData = Optional.empty();
System.out.println(data.orElseGet(() -> "")); //Hello
System.out.println(emptyData.orElseGet(() -> "")); //

NOTE: orElse() always calls the subsequent function whether you want it or not.Whereas in case of orElseGet() the execution is done if the value is empty.

orElseThrow(): Return the value if the value is present, otherwise throw the exception corresponding to the provided supplier.
Syntax : public T orElseThrow(Supplier exceptionSupplier)throws X extends Throwable

Optional dataWithNull = Optional.ofNullable(null);
String nullValue = dataWithNull.orElseThrow(IllegalArgumentException::new); //throw IllegalArgumentException

equals(): It returns true or false on the basis of the condition that the two object are equal or not. And two objects here, are equal when :
1. it is also an Optional and;
2. both instances have no value present or;
3. the present values are “equal to” each other via equals().
Syntax : public boolean equals(Object obj)


Optional data1 = Optional.of("knoldus");
Optional data2 = Optional.of("knoldus");
System.out.println(data1.equals(data2)); // true
System.out.println(data1 == data2); // false

Optional data1 = Optional.empty();
Optional data2 = Optional.empty();
System.out.println(data1.equals(data2)); // true
System.out.println(data1 == data2); // true

Key Points :
Instance fields – Use plain values. Optional wasn’t created for usage in fields. It’s not serializable and adds a wrapping overhead that you don’t need. Instead, use them on the method when you process the data from the fields.
Method parameters – Use plain values. Dealing with tons of Optionals pollutes the method signatures and makes the code harder to read and maintain. All functions can be lifted to operate on optional types where needed. Keep the code simple!
Method return values – Consider using Optional. Instead of returning nulls, the Optional type might be better. Whoever uses the code will be forced to handle the null case and it makes the code cleaner.
If we pass null to the Optional.ofNullable(), then it doesn’t throw an exception. It actually returns an empty Optional object.

In this blog, we briefly touched upon Java optional – definitely one of the most interesting Java 8 features.

There are much more advanced examples of using optional; the goal of this blog was only to provide a quick and practical introduction to what you can start doing with the functionality and as a starting point for exploring and further learning.
Demo :
https://gist.github.com/Aayush-Aggarwal/b0047c1793bbbe03ed3ac4a64d972b91

References :
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

Pasted image at 2017_11_27 04_17 PM

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 )

w

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.