Reputation: 27
I have 2 classes Employee and Manager that extends employee. i have Arraylist type Employee that contains both employees and managers. i want generic method that will create a new ArrayList type Manager that will copy all the managers from the 1st List.
Upvotes: 0
Views: 82
Reputation: 18834
Using java 8, you can use the stream methods to do the the steps Davide Lorenzo MARINO said in his answer.
- Create a new List
- Loop through the List
- For each element check if that element is a Manager using operator instanceof
- If it is a Manager add it to the List
- Return the List
Using java 8:
list.stream().filter(Manager.class::isInstance).map(Manager.class::cast).collect(Collectors.toList());
We first stream the items in the original list, filter the out the Manager
s, cast the Manager
s to Manager
instances, then collect our result in a list.
Upvotes: 1
Reputation: 26926
The steps are:
List<Manager>
List<Employee>
Manager
using operator **instanceof**
List<Manager>
List<Manager>
It should be easy translate this steps in real code.
Upvotes: 5