gymcode
gymcode

Reputation: 4623

Java Retrieve Subclass Objects from Parent Class

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

Answers (2)

MrHutnik
MrHutnik

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

azro
azro

Reputation: 54148

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
}

Upvotes: 7

Related Questions