I'd like to have a for each loop to loop through an array of objects.. but only the objects that are an instance of a specific class. To be more clear of what I mean, I've included the example below...
//Declare a list of employee objects
List<Employee> employees = new ArrayList<Employees>;
//Create some employees...
Employee employee = new Employee();
//The class EmployeeExtender extends and is a child of Employee
EmployeeExtender employeeExtended = new EmployeeExtender();
//Now add all the employees, even the ones of different instances to the list
employees.add(employee);
employees.add(employeeExtended);
Now I would like to introduce a for each loop that loops through the employees list that only loops through employees that are an instance of EmployeeExtender. I could just loop through each one and use an if statement (as shown below) but I would like to know if there was a way without making a seperate list to do this.
//I would like to only loop through employees that are an instance of EmployeeExtender
for(Employee employee : employees){
//I would like to not have this if statement...
if(employee instanceof EmployeeExtender){
//do logic...
}
}
Are my only options creating separate lists, or using the if statement? I'd like to know if there are more options. Thanks.
employees.stream().filter(e -> e instanceOf ExmployeeExtender).forEach( . . . ); well, unless you use a custom list which provides a iterator only on the objects that are instances of EmployeeExtender, but that's really just moving your filtering around.