Reputation: 4623
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
Upvotes: 2
Views: 843
Reputation: 132
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;
}
Upvotes: 3
Reputation: 54148
You need to do it by steps :
List<Person
to check all of themEmployee
you need to cast it as and keep itEmployee
1. 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
}
Upvotes: 7