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)?