Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Retrieve Subclass Objects from Parent Class

Tags:

java

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

like image 353
gymcode Avatar asked Jan 25 '26 10:01

gymcode


2 Answers

You need to do it by steps :

  1. Iterate on the List<Person to check all of them
  2. If the current element is en Employee you need to cast it as and keep it
  3. Return the list of keeped Employee

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
}
like image 103
azro Avatar answered Jan 26 '26 23:01

azro


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;
}
like image 43
MrHutnik Avatar answered Jan 27 '26 00:01

MrHutnik