Java 8 Optional Class

by Santosh K Saha | Category Java-8


Java 8 introduces a new class called java.util.Optional. The main advantage of using Optional is to avoid NullPointerException in java. It's a class that encapsulates an optional value ie it is like a container that either contains a value or doesn't (it is then said to be "empty").

Optional is never null

String s1 = //The value of s1 might be null
Optional<String> opt = //The value of opt never be null

By using Optional we can specify default values to return when something is null.


Lets understand the Optional class with examples


import java.util.Optional;

public class Person {

	private String personName;
	private Optional<Car> car;
	
	public String getPersonName() {
		return personName;
	}
	public void setPersonName(String personName) {
		this.personName = personName;
	}
	public Optional<Car> getCar() {
		return car;
	}
	public void setCar(Optional<Car> car) {
		this.car = car;
	}
}

import java.util.Optional;

public class Car {

	private String carName;
	private Optional<Insurance> insurance;
	
	public String getCarName() {
		return carName;
	}
	public void setCarName(String carName) {
		this.carName = carName;
	}
	public Optional<Insurance> getInsurance() {
		return insurance;
	}
	public void setInsurance(Optional<Insurance> insurance) {
		this.insurance = insurance;
	}
}

public class Insurance {

	private String insuranceName;

	public String getInsuranceName() {
		return insuranceName;
	}

	public void setInsuranceName(String insuranceName) {
		this.insuranceName = insuranceName;
	}
}

import java.util.Optional;

public class App {

	public static void main(String[] args) {

		// Creating Otional object
		Optional<String> empty = Optional.empty(); // Empty Optional
		System.out.println("01-->> "+empty.isPresent()); // false

		Optional<String> opt1 = Optional.of("Stosh"); // OPtional from non-null value
		System.out.println("02-->> "+opt1.isPresent()); // true

		try {
			Optional<String> opt2 = Optional.of(null); // NullPointerException
			System.out.println("03-->> "+opt2.isPresent());
		} catch (Exception e) {
			e.printStackTrace();
		}

		Optional<String> opt3 = Optional.ofNullable("Stosh"); // Optional from nullable value
		System.out.println("04-->> "+opt3.isPresent()); // true

		Optional<String> opt4 = Optional.ofNullable(null); // Optional from nullable value
		System.out.println("05-->> "+opt4.isPresent()); // flase

		opt3.ifPresent(x -> System.out.println("06-->> "+x.length())); // 5
		opt4.ifPresent(x -> System.out.println("07-->> "+x.length())); // Does not display value

		String s1 = opt3.orElse("Java"); // Default value with orElse
		String s2 = opt4.orElse("Java"); // DEfault value with orElse

		System.out.println("08-->> "+s1); // Stosh
		System.out.println("09-->> "+s2); // Java

		String s3 = opt3.orElseGet(() -> { // Default value with orElseGet
			System.out.println("10-->>"); // Not Executed
			return "Java";
		});
		String s4 = opt4.orElseGet(() -> {
			System.out.println("11-->>"); // Executed
			return "Java";
		});

		System.out.println("12-->> "+s3);
		System.out.println("13-->> "+s4);

		try {
			System.out.println("14-->> ");
			String s5 = opt3.orElseThrow(IllegalArgumentException::new);
			System.out.println("15-->> " + s5);
			String s6 = opt4.orElseThrow(IllegalArgumentException::new); // IllegalArgumentException
			System.out.println("16-->> " + s6);
			System.out.println("17--> " + s5);
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("18-->> " + opt3.get());
		// System.out.println("o-->>"+opt4.get()); //NoSuchElementException

		System.out.println("----------------------------------------------------");
		Optional<String> opt5 = opt1.filter(x -> x.equals("Stosh")); // return Optional as it is
		Optional<String> opt6 = opt1.filter(x -> x.equals("Stosh1")); // return empty Optional
																		
		System.out.println("19-->> "+opt5.isPresent()); // true
		System.out.println("20-->> "+opt6.isPresent()); // false

		System.out.println("21-->> "+opt5.get()); // Stosh
		// System.out.println("22-->> "+opt6.get()); //NoSuchElementException
		System.out.println("23-->> "+opt5.orElse("AAAA")); // Stosh
		System.out.println("24-->> "+opt6.orElse("BBBB")); // BBBB

		Optional<Integer> opt7 = opt1.map(x -> x.length()); // transforming value with map
															 
		int i = opt7.orElse(0); // 5
		System.out.println("25-->> "+i);
		System.out.println("26-->> "+opt7.get()); // 5

		
		//Cascading Optional Objects Using the flatMap Method
		Person person = new Person();
		Car car = new Car();
		Insurance insurance = new Insurance();

		insurance.setInsuranceName("Shikhar Insurance");
		car.setCarName("Mustang");
		car.setInsurance(Optional.of(insurance));
		person.setPersonName("Avisek");
		person.setCar(Optional.of(car));

		Optional<Person> optPerson = Optional.of(person);
		Optional<String> name1 = optPerson.flatMap(Person::getCar)
				.flatMap(Car::getInsurance)
				.map(Insurance::getInsuranceName);

		String name2 = optPerson.flatMap(Person::getCar)
				.flatMap(Car::getInsurance)
				.map(Insurance::getInsuranceName)
				.orElse("Unknown");

		System.out.println("27-->> "+name1.get()); // Shikhar Insurance
		System.out.println("28-->> "+name2); // Shikhar Insurance

	}

}
Output :
01-->> false
02-->> true
java.lang.NullPointerException
	at java.util.Objects.requireNonNull(Unknown Source)
	at java.util.Optional.<init>(Unknown Source)
	at java.util.Optional.of(Unknown Source)
	at com.stosh.App.main(App.java:17)
04-->> true
05-->> false
06-->> 5
08-->> Stosh
09-->> Java
11-->>
12-->> Stosh
13-->> Java
14-->> 
15-->> Stosh
java.lang.IllegalArgumentException
	at java.util.Optional.orElseThrow(Unknown Source)
	at com.stosh.App.main(App.java:54)
18-->> Stosh
----------------------------------------------------
19-->> true
20-->> false
21-->> Stosh
23-->> Stosh
24-->> BBBB
25-->> 5
26-->> 5
27-->> Shikhar Insurance
28-->> Shikhar Insurance
Note: Like our facebook page to get updated of free classes and tutorials.