Java 8 Optional Example | Avoid NullPointerException

By Arvind Rai, October 28, 2014
java.util.Optional class has been introduced in java 8, that will avoid NullPointerException in our code. We can write our code more readable and in fewer lines because now we will not apply if else condition for NullPointerException. Optional class will check for null value and if null value is present then it will return empty Optional instance. Before Java 8 we avoid NullPointerException as below.
Before Java 8
String s="None";
if(person !=null) {
    if (country != null) {
         if (primeMinister != null){
             System.out.println(name);
         }
    } 
} 
Now in Java 8, we have Optional class that can avoid NullPointerException efficiently with fewer line of code as below.
In Java 8
String pmName= person.flatMap(Person::getCountry).flatMap(Country::getPrimeMinister)
                .map(PrimeMinister::getName).orElse("None"); 
We will understand the use of Optional class in detail.

Optional.of()

of() method creates and returns the Optional instance for the given class. We can apply other method of Optional class.

Optional.map()

map() method runs the given method in the argument if the instance is not null otherwise it returns empty Optional instance. The argument which is a function cannot have Optional mapper.

Optional.orElse()

It returns the value in the Optional instance for the mapping method otherwise it returns the value provided in orElse() argument.
Now find a class named PrimeMinister.
PrimeMinister.java
package com.concretepage.util;
public class PrimeMinister {
        String name;
        public PrimeMinister(){}
        public PrimeMinister(String name){
            this.name = name;
        }    
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
} 
Find the use of Optional class with PrimeMinister class.
OptionalDemoOne.java
package com.concretepage.util;
import java.util.Optional;
public class OptionalDemoOne {
    public static void main(String[] args) {
        Optional<PrimeMinister> pm = Optional.of(new PrimeMinister());
        String pmName = pm.map(PrimeMinister::getName).orElse("None");
        System.out.println(pmName);
        //Assign Some Value to PrimeMinister.name
        pm = Optional.of(new PrimeMinister("Narendra Modi"));
        pmName = pm.map(PrimeMinister::getName).orElse("None");
        System.out.println(pmName);
    }
} 
Find the Output.
None
Narendra Modi 

Optional.flatMap()

flatMap () method is same as map() method but the difference is that the method argument which is a function must have Optional mapper.
Find some more classes. We have a Country class.
Country.java
package com.concretepage.util;
import java.util.Optional;
public class Country {
	Optional<PrimeMinister> primeMinister;
        public Country(){}
        public Country(Optional<PrimeMinister> primeMinister){
            this.primeMinister = primeMinister;
        }
	public Optional<PrimeMinister> getPrimeMinister() {
		return primeMinister;
	}
	public void setPrimeMinister(Optional<PrimeMinister> primeMinister) {
		this.primeMinister = primeMinister;
	}
} 
Another class is Person class. Country class is using PrimeMinister class and Person class is using Country class.
Person.java
package com.concretepage.util;
import java.util.Optional;
public class Person {
	Optional<Country> country;
        public Person(){}
        public Person(Optional<Country> country){
        this.country = country;
        }
	public Optional<Country> getCountry() {
		return country;
	}
	public void setCountry(Optional<Country> country) {
		this.country = country;
	}
} 
Now we have more useful example which is displaying the use of Optional class.
OptionalDemoTwo.java
package com.concretepage.util;
import java.util.Optional;
public class OptionalDemoTwo {
    public static void main(String[] args) {
        Optional<PrimeMinister> primeMinister = Optional.of(new PrimeMinister("Narendra Modi"));
        Optional<Country> country = Optional.of(new Country(primeMinister));
        Optional<Person> person = Optional.of(new Person(country));
        String pmName= person.flatMap(Person::getCountry).flatMap(Country::getPrimeMinister)
                .map(PrimeMinister::getName).orElse("None");
        System.out.println(pmName);
   }
} 
Find the Output.
Narendra Modi 

Optional.filter()

filter() method takes Predicate instance as an argument. The value in Optional instance is filtered and if filtered value is not empty then value is returned otherwise empty Optional instance is returned.
Optionalfilter.java
package com.concretepage.util;
import java.util.Optional;
import java.util.function.Predicate;
public class Optionalfilter {
    public static void main(String[] args) {
        Optional<PrimeMinister> pm = Optional.of(new PrimeMinister("Narendra Modi"));
        //Using Optional.filter
        Predicate<PrimeMinister> pmPredicate = p-> p.getName().length() > 15;
        System.out.println(pm.filter(pmPredicate));
    }
} 
Find the Output.
Optional.empty 

Optional.ifPresent()

ifPresent() method takes Consumer instance as an argument and if value is present then it run the given consumer passed as an argument otherwise do nothing.
OptionalifPresent.java
package com.concretepage.util;
import java.util.Optional;
import java.util.function.Consumer;
public class OptionalifPresent {
    public static void main(String[] args) {
        Optional<PrimeMinister> pm = Optional.of(new PrimeMinister("Narendra Modi"));
        //Using Optional.ifPresent
        Consumer<PrimeMinister> pmConsumer = (PrimeMinister p) -> System.out.println(p.getName());
        pm.ifPresent(pmConsumer);
   }
} 
Find the Output.
Narendra Modi 

Optional.isPresent()

It returns true and false value. If value is present, then returns true otherwise false.
package com.concretepage.util;
import java.util.Optional;
public class OptionalisPresent {
    public static void main(String[] args) {
        Optional<PrimeMinister> pm = Optional.of(new PrimeMinister("Narendra Modi"));
        //Using Optional.isPresent
        System.out.println(pm.isPresent());
   }
} 
Find the Output.
 true 
Now we are done with Optional class. Happy Java 8 learning.
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us