Java 8: Optional for handling NULL


Java 8 introduces a new class called java.util.Optional to overcome the headache of NullPointerException. Optional class is a type of container of optional single value that either contains a value or doesn’t (it is then said to be “empty”).

The optional class having lots of methods to deal with different cases:

Create Optional Object

Create Optional Object : Empty


Optional optionalObj=Optional.empty();

Create Optional Object: Non-Null
Optional.of() method throw NullPointerException if passing object reference is null.


YourClass yourObj=new YourClass();
Optional optionalObj=Optional.of(yourObj);

Create Optional Object: Allowed Null
Optional.ofNullable() method allowed null reference in Optional object container.


YourClass yourObj=null;
Optional optionalObj=Optional.ofNullable(yourObj);

Check Optional Object for value present

Optional.isPresent() method return boolean true/false based on any value present in Optional container.


if(optionalObj.isPresent())
{
//do something
}

Optional Object for value

if Optional.isPresent() method return true then we get value from Optional object by get() method. If value is not exist in Optional object and trying to call get() method then throw exception as NoSuchElementException


if(optionalObj.isPresent())
{
YourClass yourObj=optionalObj.get();
}

Set Optional Object default value and actions

We can use Optional.orElse() method which provide default value if Optional object is empty.


YourClass yourObj=optionalObj.orElse(new YourClass("defaut"));
</pre We can use Optional.orElseThrow() method which instread of returning default value if Optional empty , throw an exception:

YourClass yourObj = optionalObj.orElseThrow(IllegalStateException::new);

Example 1

In this example, covered all the above case.


import java.util.Optional;
public class OptionalExamples {

	public static void main(String args[]) {
		OptionalExamples java8Tester = new OptionalExamples();
	      Integer value1 = null;
	      Integer value2 = new Integer(25);

	      //Optional.ofNullable - allows passed parameter to be null.
	      Optional<Integer> firstParam = Optional.ofNullable(value1);

	      //Optional.of - throws NullPointerException if passed parameter is null
	      Optional<Integer> secondParam = Optional.of(value2);
	      System.out.println(java8Tester.sum(firstParam,secondParam));
	   }

	   public Integer sum(Optional<Integer> a, Optional<Integer> b) {
	      //Optional.isPresent - checks the value is present or not

	      System.out.println("First parameter is present: " + a.isPresent());
	      System.out.println("Second parameter is present: " + b.isPresent());

	      //Optional.orElse - returns the value if present otherwise returns
	      //the default value passed.
	      Integer value1 = a.orElse(new Integer(0));

	      //Optional.get - gets the value, value should be present
	      Integer value2 = b.get();
	      return value1 + value2;
	   }

}

Output


First parameter is present: false
Second parameter is present: true
25

Example 2

public class OptionalExaple2

	public static void main(String[] args) {
		Optional<String> completeName = Optional.ofNullable(null);
		// The isPresent() method returns true if this instance of Optional has
		// non-null value and false otherwise.
		System.out.println("Complete Name is set? " + completeName.isPresent());
		// The orElseGet() method provides the fallback mechanism in case
		// Optional has null value by accepting the function to generate the
		// default one.
		System.out.println("Complete Name: " + completeName.orElseGet(() -> "[Unknown]"));
		// The map() method transforms the current Optional’s value and returns
		// the new Optional instance.
		System.out.println(completeName.map(s -> "Hey " + s + "!").orElse("Hey Unknown!"));

		Optional<String> firstName = Optional.of("Saurabh");
		System.out.println("First Name is set? " + firstName.isPresent());
		// The orElse() method is similar to orElseGet() but instead of function
		// it accepts the default value.
		System.out.println("First Name: " + firstName.orElseGet(() -> "[Unknown]"));
		System.out.println(firstName.map(s -> "Hey " + s + "!").orElse("Hey Unnknown!"));
		System.out.println();

	}

}

Output


Complete Name is set? false
Complete Name: [Unknown]
Hey Unknown!
First Name is set? true
First Name: Saurabh
Hey Saurabh!

References

 

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