Optional Class in Java 8

Optional Class in Java 8

About Optional Class

In Java 8, Optional class was introduced to deal with null objects and NullPointerException.  Optional objects are final and immutable. An Optional is a container that may hold either a non-null value or a marker indicating that the value is absent.

Optional Class Package

This class is a public final type class that falls under java.util package. This class was introduced in JDK 1.8 version

Methods in Optional Class

Sr. NoMethodDescription
1public static<T> Optional<T> empty()It returns an empty Optional instance. No value is present for this Optional.
2public static <T> Optional<T> of(T value)Returns an Optional object of given type with the specified non-null value. If you will try to pass null value in parameter NULLPointerException will occur
3public static <T> Optional<T> ofNullable(T value)Returns an Optional object of given type, if passing parameter is non-null otherwise returns an empty optional object
4public T get() If value is present in get () of this Optional object , returns the value, otherwise throws NoSuchElementException.
5public boolean isPresent()If isPresent() calling Optional object is non-null, returns true, otherwise false
6public void ifPresent(Consumer<? super T> consumer) If this Optional object value is present, invoke the specified consumer with the value,otherwise do nothing.
7public Optional<T> filter(Predicate<? super T> predicate)When Optional object calls filter(),and the value is present also the value matches to the given predicate,   return an Optional object describing the value, otherwise return an empty Optional object
8public<U> Optional<U> map(Function<? super T, ? extends U> mapper)It returns an optional type object describing the result of applying mapping. If a value is present, apply the provided mapping function to it,and if the result is non-null, return an Optional describing the result.  Otherwise return an empty Optional.It returns NullPointerException if the mapping function is null
9public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) It returns the result of applying an Optional-bearing mapping function to the value , if a value is present, otherwise an empty Optional. This method is similar to map() but the provided mapper is already an Optional. It throws NullPointerException if the mapping function is null or returns a null result
10public T orElse(T other) It returns this Optional object value if present, otherwise returns the passing other value.Parameter other of T type is a the value to be returned if there is no value present, may be null
11public T orElseGet(Supplier<? extends T> other) Return this Optional object value if present, otherwise return the result of other.get(). 
 Parameter other is a Supplier whose result is returned if no value is present.
12public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws XReturn this Optional contained value, if present, otherwise throw an exception to be created by the provided supplier.exceptionSupplier The supplier which will return the exception to be thrown
13public boolean equals(Object obj)To check, if passing Optional object is equal to this Optional object.
14public int hashCode()It returns the hash code value of the present value, if no null, or 0 (zero) if no value is present.
15public String toString()If this Optional value is present, It returns string  representation in the result. For Empty and Optionals returned, String must be unambiguously different.

Optional Class’s Methods Explanation with Java Examples

To Understand Optional Class functions let’s create Student and School classes:

Student Class

package java8.optional.learn;


import java.util.Optional;


public class Student {
  	private String name;
	private int age;
	private String grade;
	private School school;
 
   	public Student() {
        
   	}


	public Student(String name, int age, String grade, School school) {
		super();
		this.name = name;
		this.age = age;
		this.grade = grade;
		this.school = school;
	}


	public Optional<School> getSchoolOptional() {
		return Optional.ofNullable(this.school);
	}
	
	public School getSchool() {
		return this.school;
	}	
	
	public String getName() {
		return this.name;
	}	
	
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", grade=" + grade + ", school=" + school + "]";
	}
   	
}

School Class

package java8.optional.learn;


public class School {
	private String schoolName;
	private String address;
	private String city;
	
	public School() {
		
	}
	public School(String name, String address, String city) {
		this.schoolName = name;
		this.address = address;
		this.city = city;
	}
	
	public School(String name) {
		this.schoolName = name;
	}
	
	public String getSchoolName() {
		return this.schoolName;
	}
	@Override
	public String toString() {
		return "School [schoolName=" + schoolName + ", address=" + address + ", city=" + city + "]";
	}
	
}

Let’s Understand Optional Class Functions:

1. empty()

  • Syntax : public static<T> Optional<T> empty() 
  • Description : It returns an empty Optional instance. There is no value present for this Optional object. It is a static type method. By using this method you can create an empty Optional instance of T type.
  • Parameter : no parameter
  • Return : empty Optional instance

empty() in java code : In this example we creating empty Student type Optional instance

private static void learnEmpty() {
	Optional<Student> student = Optional.empty();
	System.out.println("Student type Optional empty instance==== " + student);
	}


Output : Student type Optional empty instance==== Optional.empty

2. of()

  • Syntax : public static <T> Optional<T> of(T value)  
  • Description : It is a static method and called directly by Optional class.It returns an Optional object of given type.Passing value should be non-null value. If you try to pass null value in parameter NULLPointerException will occur.  
  • Parameter : non null value of class T type
  • Return : Optional object of passing parameter;
  • Exception : NullPointerException if passing value is null

Exception : NullPointerException if passing value is null

Example

In this example, we are creating Optional object of Student using of(). If We will pass non-null Student Object, it will create Optional Object otherwise will throw NullPoinerExceptiion. To test behavior of  this of() method we will pass both non-null and null value in  learnOptionalOf()

Java Code

private static void learnOptionalOf(Student student) {
	Optional<Student> optionalStudentObject = Optional.of(student);
	System.out.println("Optional.of Student = " + optionalStudentObject);

	}


Output:
 
Scenario #1: Passing non-null Student object in learnOptionalOf() that is created as below :
Student s = new Student("RoundTheTech",12,"4",new School("ABC", "address", "city"));

Output on Console:
Optional.of Student =  Optional[Student [name=RoundTheTech, age=12, grade=4, school=School [schoolName=ABC, address=address, city=city]]]


Scenario #2 : Passing null student object in learnOptionalOf() .

Output On Console:
Exception in thread "main" java.lang.NullPointerException
	at java.util.Objects.requireNonNull(Objects.java:203)
	at java.util.Optional.<init>(Optional.java:96)
	at java.util.Optional.of(Optional.java:108)
	at java8.optional.learn.App.learnOptionalOf(App.java:23)
	at java8.optional.learn.App.main(App.java:142)

3. ofNullable()

  • Syntax: public static <T> Optional<T> ofNullable(T value)
  • Description : Returns an Optional object of given type, if passing parameter is non-null otherwise returns an empty optional object. It is a static method and called directly by Optional class.
  • Parameter : T Type class value
  • Return : Optional Object of T class if the specified value is non-null, otherwise an empty Optional object.

Example : In this Example we are creating Optional Object of Student type using ofNullable method. To test the behavior of  this method we will pass both non-null and null values of Student in  learnOptionalOfNullable().

  •  If we pass non-null Student object, It will return Optional instance of Student Type 
  • otherwise  If we pass null Student object, It will return empty Optional instance
java Code: 	

private static Optional<Student> learnOptionalOfNullable(Student student) {

Optional<Student> optionalStudentObject = Optional.ofNullable(student);
System.out.println("Optional.ofNullable Student :: " + optionalStudentObject);
		return optionalStudentObject;
}


Output:

#1: If Student object non-null and Student Object is something like this
// Student s = new Student("RoundTheTech",12,"4",new School("ABC", "address", "city"));

Output on Console

Optional.ofNullable Student :: Optional[Student [name=RoundTheTech, age=12, grade=4, school=School [schoolName=ABC, address=address, city=city]]]


#2: If passing student object null. 

Output on Console

Optional.ofNullable Student :: Optional.empty

4. get()

  • Syntax : public T get() 
  • Description :  It is a non static method and called by Optional object. If value is present in this Optional object , returns the value, otherwise throws NoSuchElementException.
  • Parameter : No Parameter
  • Return : the non-null value held by this Optional instance
  • Exception : NoSuchElementException if this Optional Object is empty

Example :

In this example, we are getting Student Object using get() from Optional object optionalStudentObject.

  • If we pass non-null Student object in learnGet()
    1. Optional Object of Student type will be created
    2. get()  will return student Object
  • otherwise  If we pass null Student object,
    1. Empty Optional Object will be created
    2. NoSuchElementException will be thrown

Note : In Real Scenario you may already have Optional Object to apply get method. But Here we are creating an  instance of Optional <Student>  for learning purposes.

Java Code:

private static void learnGet(Student student) {

	Optional<Student> optionalStudentObject = learnOptionalOfNullable(student);
	System.out.println("Optional.get() :: " + optionalStudentObject.get());

}

Output:

Scenario #1: Passing non-null Student object something like 
//Student s = new Student("RoundTheTech",12,"4",new School("ABC", "address", "city"));

Output on Console

Optional.get() :: Student [name=RoundTheTech, age=12, grade=4, school=School [schoolName=ABC, address=address, city=city]]


Scenario #2: Passing Student Object as null
Output on Console
Exception in thread "main" java.util.NoSuchElementException: No value present
	at java.util.Optional.get(Optional.java:135)
	at java8.optional.learn.App.learnGet(App.java:35)
	at java8.optional.learn.App.main(App.java:142)

5. isPresent()

  • Syntax : public boolean isPresent() 
  • Description : It is an instance method of Optional class. It is called by Optional object. If the value of Optional object is non-null, returns true, otherwise false. 
  • Return : boolean value. True if there is a value present, otherwise false.

Example:

Here in exampleWe are calling isPresent() Method by Optional instance of Student by passing null/non-null value in parameter.

  • Passing null as parameter in learnIsPresent()
    1. Since we are passing null, Optional object will also be empty
    2. isPresnt() will return false and execute else block
  • Passing non-null parameter in learnIsPresent()
    1. Optional object  of Student type will be created
    2. isPresnt() will return true and execute if block

Note : In Real Scenario you may already have Optional Object to apply get method. But Here we are creating an  instance of Optional <Student>  for learning purposes.

private static void learnIsPresent(Student student) {

	Optional<Student> optionalStudentObject = Optional.ofNullable(student);
	if (optionalStudentObject.isPresent()) {
		System.out.println("optionalStudentObject is present." );
	}else {
		System.out.println("optionalStudentObject is not Present(). " );
	}
}

Output:

#1: If you pass non-null Student object something like 
//Student s = new Student("RoundTheTech",12,"4",new School("ABC", "address", "city"));
optionalStudentObject is present.

#2: If you are passing null Student Object
optionalStudentObject is not Present(). 

6. ifPresent()

  • Syntax : Public void ifPresent(Consumer<? super T> consumer) 
  • Description :  It is an instance method of Optional class and called by Optional object. If Optional object value is present, invoke the specified consumer with the value,otherwise do nothing.
  • Parameter : consumer block to be executed if a value is present
  • Return : N/A as void method
  • Exception : NullPointerException if value is present and consumer is  null

Example:

Here in exampleWe are calling ifPresent() Method by Optional instance of Student by passing null/non-null value in parameter. It will print school object on console only if optional object value is present.

  • Passing null as parameter in learnIfPresent()
    1. Since we are passing null, Optional object will also be empty
    2. Since Optional object value is not present, It will not do anything
  • Passing non-null parameter in learnIfPresent()
    1. Optional object  of Student type will be created
    2. ifPresnt() Consumer will be executed, will get School object from Student and print on console

Note : In Real Scenario you may already have Optional Object to apply get method. But Here we are creating an  instance of Optional <Student>  for learning purposes.

Java Code : 

private static void learnIfPresent(Student student) {

	Optional<Student> optionalStudentObject = Optional.ofNullable(student);		
	Consumer<Student> consumer = (s) -> System.out.println("Getting School :::"+s.getSchool());
	optionalStudentObject.ifPresent(consumer);
	}

OutPut:

Scenario#1:  Passing non-null Object of Student that is like
Student s = new Student("RoundTheTech",12,"4",new School("ABC", "address", "city"));

Output on Console:

Getting School :::School [schoolName=ABC, address=address, city=city]

Scenario#2:  Passing null  object

Nothing will print on Console:

7. filter()

  • Syntax : Public Optional<T> filter(Predicate<? super T> predicate)
  • Description :   It is a non static method and called by Optional object.When Optional object calls filter(),and the value is present also the value matches to the given predicate, return an Optional object describing the value, otherwise return an empty Optional object. 
  • Parameter :  a predicate, to apply to the value, if present
  • Return : return an Optional Object describing the value of calling(this) Optional object if value is present and matches to the given predicate otherwise return and empty Optional

Exception : NullPointerException if the predicate is null

Example: 

In this example we are filtering Student from Student Optional object whose school name is “ABC”

  • Creating Optional Object of passing Student ( * This step is just for learning purposes. In real scenario you may no need of this step as you may get Optional object)
  • Calling filter() by optionalStudentObject to filter students having schoolname  “ABC” 
  • If filter() definition is satisfied, method returns Optional object, which is validated by isPresent(). If isPresnt() returns true, Print a message “Student after condition check” on console.
Java Code:

private static void learnFilter(Student student) {

	Optional<Student> optionalStudentObject = Optional.ofNullable(student);
           optionalStudentObject.filter(s -> s.getSchool().getSchoolName().equals("ABC"))
				.ifPresent(s -> System.out.println("Student after condition check" + s));

}

Output on Console:
 
Student after condition check:::: Student [name=RoundTheTech, age=12, grade=4, school=School [schoolName=ABC, address=address, city=city]]

8. map()

  • Syntax : Public Optional<U> map(Function<? super T, ? extends U> mapper)
  • Description :  It is a non static method and called by Optional object. It returns an optional type object describing the result of applying mapping. If a value is present, apply the provided mapping function to it,and if the result is non-null, return an Optional describing the result.  Otherwise return an empty Optional
  • Parameter : mapper, a mapping function to apply to the value, if present
  • Return : an Optional describing the result of applying a mapping function to the value of this Optional, if a value is present,otherwise an empty  Optional
  • Exception : NullPointerException if the mapping function is null

Example 

In this example, We are Converting Student type Optional Object to uppercase if  school name is “ABC”

  • Creating Optional Object of passing Student ( * This step is just for learning purposes. In real scenario you may no need of this step as you may get Optional object)
  • Calling filter() by optionalStudentObject to filter students having school name  “ABC” 
  • If filter() definition is satisfied, map() will convert it to uppercase 
  • Getting Student Object using get()
Java Code:

private static void learnMap(Student student) {

	Optional<Student> optionalStudentObject = Optional.ofNullable(student);
	String str = optionalStudentObject
				.filter(s -> s.getSchool().getSchoolName().equals("ABC"))
				.map(s -> s.toString().toUpperCase()).get();
	System.out.println("Learn Optional map() :::" + str);
	}

Output on Console:

Learn Optional map() :::STUDENT [NAME=ROUNDTHETECH, AGE=12, GRADE=4, SCHOOL=SCHOOL [SCHOOLNAME=ABC, ADDRESS=ADDRESS, CITY=CITY]]

9. flatMap()

  1. Syntax : Public Optional<U>  flatMap(Function<? super T, Optional<U>> mapper) 
  2. Description : It is a non static method and called by Optional object.when we have nested Optionals (Optional<Optional<String>>), we can use the flatMap() method to flatten the result.

The flatMap method takes a Function as its argument, which maps the value inside the Optional to another Optional. It then returns the result as a flattened Optional or an empty Optional if any of the Optional instances involved are empty.  

  • Parameter : mapper a mapping function to apply to this Optional value, if present the mapping function. Parameter is Optional type.
  • Return : returns the result of applying an Optional-bearing mapping function to the value , if a value is present, otherwise an empty Optional. This method is similar to map() but the provided mapper is already an Optional. It throws NullPointerException if the mapping function is null or returns  null result
  • Exception : NullPointerException if the mapping function is null or returns

Example :

In this we are getting School object using flatMap() for the Optonal object of Student type which is having Optional<School> inside.

  • We are creating Optional<Student> optionalStudentObject  ( * This step is just for learning purposes. In real scenario you may no need of this step as you may get Optional object already).Student class returns Optional<School> object by getSchoolOptional() method.
  • Here firstly, We are using map() to understand the difference of map() and flatMap(). If we call map(), it returns Optional<School> object 
  • By if we call  flatMap(), we directly get the school object.
private static void learnFlatMap(Student student) {

	Optional<Student> optionalStudentObject = Optional.ofNullable(student);
		
	//this statement will return Optional<School> object
	Optional<School> optionalSchool = optionalStudentObject.map(s -> s.getSchoolOptional()).get();
		
	//using flatMap(), returns school object
	School school = optionalStudentObject.flatMap(s -> s.getSchoolOptional()).get();
 
	System.out.println("Using Map, Getting Optional<School> object:::: " + optionalStudentObject);
	System.out.println("Using flatMap, Getting directly school object:::: " + school);
	}

Output on Console

Using Map, Getting Optional<School> object:::: Optional[Student [name=RoundTheTech, age=12, grade=4, school=School [schoolName=ABC, address=address, city=city]]]

Using flatMap, Getting directly school object:::: School [schoolName=ABC, address=address, city=city]

10. orElse()

  • Syntax : Public T orElse(T other) 
  • Description :   It is a non static method and called by Optional object. It returns this Optional value if present, otherwise returns the other value.Parameter T is the value to be returned if there is no value present, may be null. 
  • Parameter : other, the value to be returned if calling this Optional value is not present
  • Return : the value, if present, otherwise passing other value

Example :

 In this Example, We are  creating a new Student object if Optional Object of Student is empty.

  • We are creating Optional<Student> optionalStudentObject  ( * This step is just for learning purposes. In real scenario you may no need of this step as you may get Optional object already).Student class returns Optional<School> object by getSchoolOptional() method.
  • if passing Student object in parameter is null.  Optional object of this null student will be empty. So orElse() will create  new Student object 
  • if passing Student object in parameter is not null. Optional object will have value and orElse() method will  not  br executed .
Java Code

private static void learnOrElse(Student student) {

	Optional<Student> optionalStudentObject = Optional.ofNullable(student);
	//New Student object will be created if optionalStudentObject is empty
	Student s = optionalStudentObject.orElse(new Student());
	System.out.println("Student object :::" + s);
	}

Output:

#1. If student object is null, New instance of student
Output on Console
Student object :::Student [name=null, age=0, grade=null, school=null]

#if student object  is not Null
Output on Console
Student object :::Student [name=RoundTheTech, age=12, grade=4, school=School [schoolName=ABC, address=address, city=city]]

11. orElseGet()

  • Syntax : Public T orElseGet(Supplier<? extends T> other)
  • Description :  It is a non static method and called by Optional object. It returns the value if present, otherwise invoke other and returns the result of that invocation.
  • Parameter : other, a Supplier whose result is returned if no value present
  • Return : the value if present otherwise the result of other.get()
  • Exception : NullPointerException if value is not present and other is null

Example :

In this Example, We are  creating a new Student object by Supplier if Optional Object of Student is empty.

  • We are creating Optional<Student> optionalStudentObject  ( * This step is just for learning purposes. In real scenario you may no need of this step as you may get Optional object already).Student class returns Optional<School> object by getSchoolOptional() method.
  • if passing Student object in parameter is null.  Optional object of this null student will be empty. So orElseGet Supplier definition  will create  new Student object 
  • if passing Student object in parameter is not null. Optional object will have value and  orElseGet() method will  not be executed .
Java Code

private static void learnOrElseGet(Student student) {

	Optional<Student> optionalStudentObject = Optional.ofNullable(student);
	Student s = optionalStudentObject.orElseGet(() -> new Student());
	System.out.println("learnOrElseGet method in Optional :::" + s);
}


Output:

#1 : if Object is not null
OrElseGet method ::Student [name=RoundTheTech, age=12, grade=4, school=School [schoolName=ABC, address=address, city=city]]


#2 : if Object is null
OrElseGet method ::Student [name=null, age=0, grade=null, school=null]

12.  orElseThrow()

  • Syntax : Public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X
  • Description : It is a non-static method and called by Optional object. It returns the contained value, if present, otherwise throws an exception to be created by the provided supplier. 
  • Parameter : exceptionSupplier, The supplier which will return the exception to be thrown.If this Optional object value not present throw exceptionSupplier exception
  • throws  : X if there is no value present
  • Exception : NullPointerException if no value is present and exceptionSupplier is null

Example : 

In this Example, We are  throwing Runtime exception by Supplier if Optional Object of Student is empty.

  • We are creating Optional<Student>  object from the passing Student parameter ( * This step is just for learning purposes. In real scenario you may no need of this step as you may get Optional object already).Student class returns Optional<School> object by getSchoolOptional() method.
  • if passing Student object in parameter is null, Empty Optional object will be created. And orElseThrow() will create  supply RuntimeException

if passing Student object in parameter is not null. Optional object of this student will have value and orElseThrow() method will not be executed .

Java Code:

private static void learnOrElseThrow(Student student) {

	Optional<Student> optionalStudentObject = Optional.ofNullable(student);
	Student s = optionalStudentObject.orElseThrow(() -> new RuntimeException("Student Object is  null"));
	System.out.println("learnOrElseThrow method :::" + s);

}

Output:

#1: if passing Student object is null
Output on Cosole
Exception in thread "main" java.lang.RuntimeException: Student Object is  null
	at java8.optional.learn.App.lambda$7(App.java:103)
	at java.util.Optional.orElseThrow(Optional.java:290)
	at java8.optional.learn.App.learnOrElseThrow(App.java:103)
	at java8.optional.learn.App.main(App.java:160)

#2: if passing Student object is not null
Output on Cosole
learnOrElseThrow method :::Student [name=RoundTheTech, age=12, grade=4, school=School [schoolName=ABC, address=address, city=city]]

13.  equals()

  • Syntax : Public  boolean equals(Object obj)
  • Description : It is a non static method and called by Optional object.  This method checks if passing Optional object is equal to this Optional object or not.
  • Parameter : Object to test the equality with this Optional Object
  • Return :  boolean value, true if both are equal otherwise false

Example : 

In the example , we are creating 2 Optional Objects  of String type with different values (“value1” and “ “value2”). Checking both optional objects equality and printing the result on console accordingly. 

Java Code

	private static void learnEquals() {

		Optional<String> optionalValue1 = Optional.ofNullable("value1");
		Optional<String> optionalValue2 = Optional.ofNullable("value2");
		String value = (optionalValue1.equals(optionalValue2)) == true ? "equals" : "Not equal";

		System.out.println("Is value1 and value2 equal :::" + value);
	}


Output: on console

Is value1 and value2 equal :::Not equal

14. hashCode()

  • Syntax: Public int hashCode()
  • Description :  It is a non static method and called by Optional object. It returns the hash code of this Optional value, if non null, or 0 (zero) if no value is present. 
  • Parameter : No Parameter
  • Return : hash code value of this Optional value or 0 if no value is present

Example :

We are getting hash code of String type Optional object having value “value1”

Java Code:

	private static void learnHashCode() {
		Optional<String> optionalValue1 = Optional.ofNullable(new String("value1"));
		System.out.println("optionalValue1 hashcode :" + optionalValue1.hashCode());
	}

Output:

optionalValue1 hashcode :-823812896

15.  toString()

  • Syntax : Public  String toString()
  • Description : It is an instance method and called by Optional object. If a value is present, It returns string  representation in the result. 
    For Empty and Optionals returned String must be unambiguously different.
  • Parameter :  No Parameter
  • Return : the string representation of this instance

Example :

Here in this Example, We are testing toString() of Optional class on String type Optional object having value “value1”

java Code: 	

private static void learnToString() {

	Optional<String> optionalValue = Optional.ofNullable("RoundTheTech");
	System.out.println("learnToString:::" + optionalValue);
}

Output on Console:

learnToString:::Optional[RoundTheTech]

Differences Between ifPresent() and isPresent()

AspectifPresent()isPresent
SyntaxifPresent(Consumer<? super T> consumer) public boolean isPresent()
return  typeVoid type methodboolean return type.Return true if there is a value present, otherwise false
ParameterConsumer type parameterNo parameter
ExceptionThrow NullPointerException if value is present and consumer is  nullNo Exception
PurposeUsed to execute a specified action only if the Optional contains a non-null value. It takes a consumer function as an argument.Used to check if the Optional contains a non-null value. It returns a boolean (true if a value is present, false if it’s empty).

Differences Between map() and flatMap()

Aspectmap MethodflatMap Method
ParameterTakes a Function as prameter that maps the value inside the Optional to another valueTakes a Function that maps the value inside the Optional to another Optional.
Return typeReturns an Optional containing the result of the mapping function. If the Optional is empty, it remains empty.Returns the Optional resulting from the mapping function. If the Optional is empty, it remains empty.
Nested OptionalsDoes not handle nested Optional instances well. If the mapping function returns an Optional, you may end up with nested Optional instances.Flattens the result of the mapping function automatically, so you won’t get nested Optional instances.
Use CaseUsed when you want to transform the value inside the Optional and you don’t expect the mapping function to return another Optional.Used when you want to transform the value inside the Optional, and the mapping function itself may return an Optional.

Conclusion

The Optional class helps in writing more robust and readable code by making it explicit when a value might be absent. However, it’s important to use Optional judiciously and not to overuse it, as it can sometimes lead to unnecessarily complex code. It’s commonly used when designing APIs to clearly indicate the possibility of null values without throwing NullPointerExceptions.

Java Class with all tset functions used in this article. You can comment/uncomment in main method to understand each functions accodinllgy.

package java8.optional.learn;

import java.util.Optional;
import java.util.function.Consumer;

public class App {

	private static void learnEmpty() {
		Optional<Student> student = Optional.empty();
		System.out.println("Student type Optional empty instance:::: " + student);
	}

	private static void learnOptionalOf(Student student) {
		Optional<Student> optionalStudentObject = Optional.of(student);
		System.out.println("Optional of Student :: " + optionalStudentObject);

	}

	private static Optional<Student> learnOptionalOfNullable(Student student) {

		Optional<Student> optionalStudentObject = Optional.ofNullable(student);
		System.out.println("Optional.ofNullable Student :: " + optionalStudentObject);
		return optionalStudentObject;
	}

	private static void learnGet(Student student) {

		Optional<Student> optionalStudentObject = Optional.ofNullable(student);

		System.out.println("Optional.get() :: " + optionalStudentObject.get());

	}

	private static void learnIsPresent(Student student) {

		Optional<Student> optionalStudentObject = Optional.ofNullable(student);
		if (optionalStudentObject.isPresent()) {
		System.out.println("optionalStudentObject is present." );
		}else {
			System.out.println("optionalStudentObject is not Present(). " );
		}
	}

	private static void learnIfPresent(Student student) {

		Optional<Student> optionalStudentObject = Optional.ofNullable(student);		
		Consumer<Student> consumer = (s) -> System.out.println("Getting School :::"+s.getSchool());
		optionalStudentObject.ifPresent(consumer);
	}

	private static void learnFilter(Student student) {

		Optional<Student> optionalStudentObject = Optional.ofNullable(student);

		optionalStudentObject.filter(s -> s.getSchool().getSchoolName().equals("ABC"))
				.ifPresent(s -> System.out.println("Student after condition check:::: " + s));
	}

	private static void learnMap(Student student) {

		Optional<Student> optionalStudentObject = Optional.ofNullable(student);
		String str = optionalStudentObject
				.map(s -> s.toString().toUpperCase()).get();
		System.out.println("Learn Optional map() :::" + str);
	}

	private static void learnFlatMap(Student student) {

		Optional<Student> optionalStudentObject = Optional.ofNullable(student);
		
		//this statement will return Optional<School> object
		Optional<School> optionalSchool = optionalStudentObject.map(s -> s.getSchoolOptional()).get();
		
		//using flatMap(), returns school object
		School school = optionalStudentObject.flatMap(s -> s.getSchoolOptional()).get();
 
		System.out.println("Using Map, Getting Optional<School> object:::: " + optionalStudentObject);
		System.out.println("Using flatMap, Getting directly school object:::: " + school);
	}
	
	private static void learnOrElse(Student student) {

		Optional<Student> optionalStudentObject = Optional.ofNullable(student);
		//New Student object will be created if optionalStudentObject is empty
		Student s = optionalStudentObject.orElse(new Student());
		System.out.println("Student object :::" + s);
	}

	private static void learnOrElseGet(Student student) {

		Optional<Student> optionalStudentObject = Optional.ofNullable(student);
		Student s = optionalStudentObject.orElseGet(() -> new Student());
		System.out.println("OrElseGet method ::" + s);
	}

	private static void learnOrElseThrow(Student student) {

		Optional<Student> optionalStudentObject = Optional.ofNullable(student);
		Student s = optionalStudentObject.orElseThrow(() -> new RuntimeException("Student Object is  null"));
		System.out.println("learnOrElseThrow method :::" + s);
	}

	private static void learnEquals() {

		Optional<String> optionalValue1 = Optional.ofNullable("value1");
		Optional<String> optionalValue2 = Optional.ofNullable("value2");
		String value = (optionalValue1.equals(optionalValue2)) == true ? "equals" : "Not equal";

		System.out.println("Is value1 and value2 equal :::" + value);
	}

	private static void learnHashCode() {
		Optional<String> optionalValue1 = Optional.ofNullable(new String("value1"));
		System.out.println("optionalValue1 hashcode :" + optionalValue1.hashCode());
	}

	

	private static void learnToString() {

		Optional<String> optionalValue = Optional.ofNullable("RoundTheTech");
		System.out.println("learnToString:::" + optionalValue);
	}



	public static void main(String[] args) {
    	learnEmpty();

    	//Use it If wanted to pass Student non-null object
    	Student s = new Student("RoundTheTech",12,"4",new School("ABC", "address", "city"));
    	
    	//Use it If wanted to pass Student null object
//		Student s = null;
    	
    	learnEmpty();
    	
		learnOptionalOf(s);
    	learnOptionalOfNullable(s);
    	learnGet(s);
    	learnIsPresent(s);
    	learnIfPresent(s);    	
    	learnFilter(s);
    	learnMap(s);
    	learnFlatMap(s);
    	learnOrElse(s);
    	learnOrElseGet(s);
    	learnOrElseThrow(s);
    	learnEquals();
    	learnHashCode();
    	learnToString();
	}
}

P.S. We welcome your feedback. Please comment, if you find anything incorrect, or want to share more information about the topic or want to share any kind of feedback.

Leave a Reply

Your email address will not be published. Required fields are marked *