Home Java How To Avoid NoSuchElementException – Java Streams

How To Avoid NoSuchElementException – Java Streams

0
717
DJ Exception
DJ Exception

In this journal blog, we will have a look at the solution for the problem “How To Avoid NoSuchElementException” while working with Java Streams.

Lets first create a sample model class to explain this scenario.

public class Employee {
    private int employeeId;
    private String employeeName;
    private int employeeAge;
    private int employeeGender;
    public Employee() {}
    public Employee(int id, String name) {
    	this.employeeId = id;
    	this.employeeName = name;
    }
    public int getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }
    public String getEmployeeName() {
        return employeeName;
    }
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
    public int getEmployeeAge() {
        return employeeAge;
    }
    public void setEmployeeAge(int employeeAge) {
        this.employeeAge = employeeAge;
    }
    public int getEmployeeGender() {
        return employeeGender;
    }
    public void setEmployeeGender(int employeeGender) {
        this.employeeGender = employeeGender;
    }
}

As you can see in the above example, we have created an Employee model class which overrides the equals method based on the employeeName. Now, in the next part we will create a list of employees which will be used to iterate and find an employee based on the search filter of the name.

List<Employee> employeeList = new ArrayList<Employee>();
Employee emp1 = new Employee(1, "Coder");
Employee emp2 = new Employee(2, "Developer");
Employee emp3 = new Employee(3, "Geek");
Employee emp4 = new Employee(4, "Scorpion");
Employee emp5 = new Employee(5, "TechNerd");
employeeList.add(emp1);
employeeList.add(emp2);
employeeList.add(emp3);
employeeList.add(emp4);
employeeList.add(emp5);

The employeeList in the above example contains the ID and Name of 5 (five) employees. Now, here comes the main part.

Employee emp = employeeList.stream().filter(x -> x.getEmployeeName().equals("TechNerd1")).findFirst().get();
LOG.info(emp.getEmployeeId() + ", " + emp.getEmployeeName());

If you run the above code, you should see the following error message:

Caused by: java.util.NoSuchElementException: No value present

To handle this type of exception, we need to understand the basics of findFirst() method.

findFirst(): Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned.

REF: Java Docs

Now, lets re-write the above lines.

Optional<Employee> emp = employeeList.stream().filter(x -> x.getEmployeeName().equals("TechNerd1")).findFirst();
//CHECK IF THE emp OBJECT HAS VALUE
if(emp.isPresent()) {
    LOG.info(emp.get().getEmployeeId() + ", " + emp.get().getEmployeeName());
} else {
    LOG.info("Employee Not Found...");
}

The above code will use the Optional isPresent() method which will return true if the object has value otherwise false. The output of the above statement is:

Employee Not Found...

Lets run the same statement again but using the correct value this time.

Optional<Employee> emp = employeeList.stream().filter(x -> x.getEmployeeName().equals("TechNerd")).findFirst();
//CHECK IF THE emp OBJECT HAS VALUE
if(emp.isPresent()) {
    LOG.info(emp.get().getEmployeeId() + ", " + emp.get().getEmployeeName());
} else {
    LOG.info("Employee Not Found...");
}

The output of the above statement is:

5, TechNerd