Skip to content

Instantly share code, notes, and snippets.

@adityachaudhari
Created October 7, 2021 17:21
Show Gist options
  • Save adityachaudhari/a3283fa33224085a18c34630d09f4df9 to your computer and use it in GitHub Desktop.
Save adityachaudhari/a3283fa33224085a18c34630d09f4df9 to your computer and use it in GitHub Desktop.
Optional in java 8 understanding
package com.java8.optional;
import com.java8.businessdataobjects.Student;
import java.util.*;
public class OptionalUnderstanding {
public static void main(String[] args) {
System.out.println("********** 3 ways to create optional instance *****************");
System.out.println("1. from potential null value, 2. from non-null value, 3. empty Optionnal object");
Car car1 = null;
Car car2 = new Car();
// Creating optional from optional null / nonnull reference
Optional<Car> optCar1 = Optional.ofNullable(car1);
Optional<Car> optCar2 = Optional.ofNullable(car2);
System.out.println(" From potential null value - using Optional.ofNullable : " + optCar1);
System.out.println(" From potential non-null value - usingOptional.ofNullable : " + optCar2);
// creating optional from non-null reference . i.e. when we are sure that reference is non null
String str = "dsgsgfd";
//String str=null; if str is null and we use Optional.Of this ll throw null pointer.
Optional<String> nonNullObject = Optional.of(str);
System.out.println("2. From non-null using Optional.Of : " + nonNullObject);
Optional<Car> optCarEmptyObj = Optional.empty();
System.out.println("3. Creating optional empty object : " + optCarEmptyObj);
// creating optional usnig existing method returning null and we wrap that null to Optional object.
Map<String, String> deliveryCoutriesIsoCodesMap = new HashMap<>();
deliveryCoutriesIsoCodesMap.put("IN", "India");
deliveryCoutriesIsoCodesMap.put("US", "United States");
deliveryCoutriesIsoCodesMap.put("UK", "United Kingdom");
System.out.println("\n**************** returning custom default value in case of potential null *********");
System.out.println("get country name for JP : " + Optional.ofNullable(deliveryCoutriesIsoCodesMap.get("JP")).orElse("NOT_FOUND"));
System.out.println("get country name for UK : " + Optional.ofNullable(deliveryCoutriesIsoCodesMap.get("UK")).orElse("NOT_FOUND"));
//deliveryCoutriesIsoCodesMap.get("FF"); in code below returns null
//System.out.println("reference to null : "+ deliveryCoutriesIsoCodesMap.get("FF").length()); // this code throws null pointer.
System.out.println("\n*************** using Optional with existing code base which returns null from method or holds null reference ******************");
List<Student> studentList = Arrays.asList(new Student(10, "Ram D", 20), new Student(18, "Zeck C", 19), new Student(11, "Tom P", 23), new Student(9, "Ronny D", 19), new Student(13, "John P", 20));
// withoug using Optional for existing reference(method / variables)
//System.out.println("Get student name without optional produces NullPointerException : "+findStudentByRollNo(10).getName());
// using Optional for existing reference(method / variables)
Optional<Student> optionalStudentByRollNo = Optional.ofNullable(findStudentByRollNo(10));
System.out.println("Get student name with optional helps to avoid NullPointerException : " + (optionalStudentByRollNo.isPresent() ? optionalStudentByRollNo.get().getName() : "INVALID_ID"));
}
static Student findStudentByRollNo(Integer rollNo) {
//some business logic which calls DAO and return a Student object or returns null for this example we ll just pass null
return null;
}
}
Result of execution :
********** 3 ways to create optional instance *****************
1. from potential null value, 2. from non-null value, 3. empty Optionnal object
From potential null value - using Optional.ofNullable : Optional.empty
From potential non-null value - usingOptional.ofNullable : Optional[com.java8.optional.Car@6e0be858]
2. From non-null using Optional.Of : Optional[dsgsgfd]
3. Creating optional empty object : Optional.empty
**************** returning custom default value in case of potential null *********
get country name for JP : NOT_FOUND
get country name for UK : United Kingdom
*************** using Optional with existing code base which returns null from method or holds null reference ******************
Get student name with optional helps to avoid NullPointerException : INVALID_ID
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment