Is it possible to write a method which allows me to take in a List of objects belonging to a Parent class Person.
Under Person class, there are several subclasses, which includes Employee class.
I want the method to return a separate List which consists of just the Employee objects from the original list.
Thank you
You need to do it by steps :
List<Person to check all of themEmployee you need to cast it as and keep itEmployee1. Classic way with foreach-loop
public static List<Employee> getEmployeeListFromPersonList(List<Person> list) {
List<Employee> res = new ArrayList<>();
for (Person p : list) { // 1.Iterate
if (p instanceof Employee) { // 2.Check type
res.add((Employee) p); // 3.Cast and keep it
}
}
return res;
}
2. Java-8 way with Streams
public static List<Employee> getEmployeeListFromPersonList(List<Person> list) {
return list.stream() // 1.Iterate
.filter(Employee.class::isInstance) // 2.Check type
.map(Employee.class::cast) // 3.Cast
.collect(Collectors.toList()); // 3.Keep them
}
Do you mean something like:
List<Employee> getEmployees(List<Person> personList){
List<Employee> result = new ArrayList<Employee>();
for(Person person : personList){
if(person instanceof Employee) result.add((Employee)person);
}
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With