Java 8 Optional Class

Java 8 introduced a new public final class Optional in java.util package. It is used to deal with NullPointerException in java application. It provides the methods to easily check whether a variable has null value or not.

Commonly used methods of Java Optional class:

Optional.ofNullable(): It returns a Non-empty Optional if the given object has a value, otherwise it returns an empty Optional. isPresent(): It is used check whether the particular Optional object is empty or no-empty. ifPresent(): It only executes if the given Optional object is non-empty.

Collectors is a final class that extends the Object class which provides reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, grouping etc.

Java example without using Optional

package com.w3schools;


public class TestExample {
	public static void main(String args[]){
	String[] str = new String[10];  
        String lowerCaseString = str[4].toLowerCase();  
        System.out.print(lowerCaseString);  
	}  
}

Output

Exception in thread "main" java.lang.NullPointerException
	at com.w3schools.TestExample.main(TestExample.java:7)

Java Optional: If Value is not Present

package com.w3schools;

import java.util.Optional;

public class TestExample {
	public static void main(String args[]){
	String[] str = new String[10];  
        Optional checkNull = Optional.ofNullable(str[4]);  
        //Check for value is present or not
        if(checkNull.isPresent()){    
            String lowerCaseString = str[4].toLowerCase();  
            System.out.print(lowerCaseString);  
        }else  {
            System.out.println("String value is not present");  
        }  
	}  
}

Output

String value is not present

Java Optional example

package com.w3schools;

import java.util.Optional;

public class TestExample {
	public static void main(String args[]){
	String[] str = new String[10];    
	// Setting value for 4th index
        str[4] = "Optional class example by W3spoint";    
        // It returns an empty instance of Optional class   
        Optional empty = Optional.empty();  
        System.out.println(empty);  
        // It returns a non-empty Optional  
        Optional value = Optional.of(str[4]);  
        // If value is present, it returns an Optional otherwise returns an empty Optional  
        System.out.println("Filtered value: "+value.filter((s)->s.equals("Abc")));  
        System.out.println("Filtered value: "+value.filter((s)->s.equals("Optional class example by W3spoint")));  
        // It returns value of an Optional. if value is not present, it throws an NoSuchElementException    
        System.out.println("Getting value: "+value.get());  
        // It returns hashCode of the value  
        System.out.println("Getting hashCode: "+value.hashCode());  
        // It returns true if value is present, otherwise false  
        System.out.println("Is value present: "+value.isPresent());  
        // It returns non-empty Optional if value is present, otherwise returns an empty Optional  
        System.out.println("Nullable Optional: "+Optional.ofNullable(str[5]));  
        // It returns value if available, otherwise returns specified value,  
        System.out.println("orElse: "+value.orElse("Value is not present"));  
        System.out.println("orElse: "+empty.orElse("Value is not present")); 
       //printing value by using method reference 
        value.ifPresent(System.out::println);     
	}  
}

Output

Optional.empty
Filtered value: Optional.empty
Filtered value: Optional[Optional class example by W3spoint]
Getting value: Optional class example by W3spoint
Getting hashCode: -1565495299
Is value present: true
Nullable Optional: Optional.empty
orElse: Optional class example by W3spoint
orElse: Value is not present
Optional class example by W3spoint
Please follow and like us:
Content Protection by DMCA.com