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.
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."));
}