Asaf.e
Asaf.e

Reputation: 27

how to create new Arraylist from other type

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

Answers (2)

Ferrybig
Ferrybig

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 Managers, cast the Managers to Manager instances, then collect our result in a list.

Upvotes: 1

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

The steps are:

  • Create a new List<Manager>
  • Loop through the List<Employee>
  • For each element check if that element is a Manager using operator **instanceof**
  • If it is a Manager add it to the List<Manager>
  • Return the List<Manager>

It should be easy translate this steps in real code.

Upvotes: 5

Related Questions