Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get rid of NullPointerException in a method using Streams API and Optional?

Given the following task.
We have an Employee and a Company classes. Each instance of Employee class is stored in array Employee[] employees in the Company class. I need a method which finds an instance of Employee in the array Employee[] employees by id.

I managed to write the following code:

public class Employee {
    protected final int id;
    protected String name;

    public Employee(int id, String name) {
        this.id = id;
        this.name= name;
    }
    public int getId() {
        return id;
    }
}

public class Company {
    private Employee[] employees;
    private int size;
    private static final int defaultCapacity = 5;
    
    public Company() {
        this(defaultCapacity);
    }
    
    public Company(int capacity) {
        if (capacity <= 0)
             throw new RuntimeException("capacity is required");
        employees = new Employee[capacity];
    }

    public Employee findEmployee(int id) {
        for (int i = 0; i < size; i++) {
            if(employees[i].getId() == id) {
                return employees[i];
            }
        }
        return null;
    }
}

The problem is that my method public Employee findEmployee(int id) throws NullPointerException if an element of the Employee[] employees equals null.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I rewrite the method public Employee findEmployee(int id) using Streams API and Optional in order to get rid of NullPointerException in the method public Employee findEmployee(int id)?

>Solution :

Something like this:

public Optional<Employee> findEmployee(int id) {
    return Stream.of(employees)
            .filter(Objects::nonNull) // <---------------
            .filter(employee -> employee.getId() == id)
            .findFirst();
}

This will return an empty Optional if no result is found. The first filter will filter all non-null employees, then the second filter will check the id.


If you want to get Employee instead of Optional, then you can use:

public Employee findEmployee(int id) {
    return Stream.of(employees)
            .filter(Objects::nonNull)
            .filter(employee -> employee.getId() == id)
            .findFirst()
            .orElse(null);
}

Or if you want to go deeper, you even throw an exception if no employee is found, for example:

public Employee findEmployee(int id) {
    return Stream.of(employees)
            .filter(Objects::nonNull)
            .filter(employee -> employee.getId() == id)
            .findFirst()
            .orElseThrow(() -> new RuntimeException("No employee found."));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading