[英]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
. 是否可以编写一个方法,允许我接受属于父类
Person
的对象列表。
Under Person
class, there are several subclasses, which includes Employee
class. 在
Person
类下,有几个子类,包括Employee
类。
I want the method to return a separate List which consists of just the Employee
objects from the original list. 我希望该方法返回一个单独的List,该List仅包含原始列表中的
Employee
对象。
Thank you 谢谢
You need to do it by steps : 您需要按步骤执行:
List<Person
to check all of them List<Person
来检查所有这些 Employee
you need to cast it as and keep it Employee
,则需要将其转换为并保留它 Employee
Employee
列表 1. Classic way with foreach-loop
1.具有
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
2.使用
Streams
Java-8方式
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.