Java 8 : Optional

When you code something in your day to day life, definitely you must have encountered the Null Pointer Exception. That causes a Lot of inconvenience to the developer’s as figuring the null value and all that literally takes a lot of time. But what if I say if there is an efficient way to avoid NullPointerException in Java 8.

Let’s take a situation where we get a Null Pointer Exception.

import java.util.*;

class Student {

private String name;
private int empId;

public Student(String name, int empId) {
    super();
    this.name = name;
    this.empId = empId;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getId() {
    return empId;
}
public void setId(int empId) {
    this.empId = empId;
}

}

public class MyClass {

public static void main(String[] args)
{
    List<Student> studList = createStudList();
    Student stud = getStudent(studList,"Hifa");
    System.out.println("Student Name: "+stud.getName());

}

public static List<Student> createStudList()
{
    List<Student> studList=new ArrayList<Student>();

    Student s1=new Student("Sumo",215012);
    Student s2=new Student("Shiji",222432);
    Student s3=new Student("Lufo",310131);

    studList.add(s1);
    studList.add(s2);
    studList.add(s3);

    return studList;
}

public static Student getStudent(List<Student> studList,String name)
{
    for(Student s:studList)
    {
        if(s.getName().equalsIgnoreCase(name))
        {
            return s;
        }
    }
    return null;
}

}

If you see above we get a Null Pointer Exception. This is because we called the getName method on a Null object. The object was NULL because there was no Student named as Hifa.

So now how to efficiently handle these scenarios?

Here comes the Optional Class in Java 8. We apply the Optional Wrapper on any Class Object and it returns an Optional type of it. It contains some methods using which we can check if Object is actually present inside the Optional instance. If it is present, then using the get method we would get the actual object from the Optional Instance.

Let’s take the same above example and try to implement the same using Optional.


import java.util.*;

class Student {

private String name;
private int empId;

public Student(String name, int empId) {
    super();
    this.name = name;
    this.empId = empId;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getId() {
    return empId;
}
public void setId(int empId) {
    this.empId = empId;
}
}
 
public class MyClass {
 
    public static void main(String[] args)
    {
        List<Student> studList = createStudList();
        Optional<Student> studOptional = getStudent(studList,"Hifa");
        if(studOptional.isPresent())
        {
            Student stud = studOptional.get();
            System.out.println("Student Name: "+stud.getName());
        }
        else
        {
            System.out.println("No student with name as Hifa");
        }
    }
 
    public static List<Student> createStudList()
    {
        List<Student> studList=new ArrayList<Student>();
 
        Student s1=new Student("Sumo",21);
        Student s2=new Student("Shiji",22);
        Student s3=new Student("Lufo",31);
 
        studList.add(s1);
        studList.add(s2);
        studList.add(s3);
 
        return studList;
    }
 
    public static Optional<Student> getStudent(List<Student> studList,String name)
    {
        for(Student s:studList)
        {
            if(s.getName().equalsIgnoreCase(name))
            {
                return Optional.of(s);
            }
        }
        return Optional.empty();
    }
}

So here using Optional it was much more efficient to handle such kind of null pointer exceptions.

Let’s look at some other methods other than get and isPresent methods which we saw above.

  1. Optional<Student> opt = Optional.empty();
  2. ifPresent:
public static void main(String[] args)
{
    List<Student> studList = createStudList();
    Optional<Student> studOpt = getStudent(studList,"Sumo");

    studOpt.ifPresent((student)->System.out.println("Student Name: "+student.getName()+" is Found!!! "));

}

3. orElse: You can return a default value if there is no value in Optional using orElse method.

public static void main(String[] args)
    {
        List<Student> studList = createStudList();
        Optional<Student> studOpt = getStudent(studList,"Somi");
 
        
        Student stud = studOpt.orElse(new Student("Mr X",0));
        System.out.println("Student name is : "+stud.getName());
 
    }

Hope the article was clear. Thanks a lot for reading.