Reputation: 177
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.
Upvotes: 1
Views: 1118
Reputation: 79875
One option that hasn't been considered is to dispatch the logic to an empty method, that's overridden in the subclass you're interested in. I don't think I'd recommend doing it this way, but you did ask for options other than the straightforward for-each / instanceof way of doing it.
public class Employee {
public void doTheLogic(TheClassYoureCallingFrom caller) {
}
}
public class EmployeeExtended extends Employee {
@Override
public void doTheLogic(TheClassYoureCallingFrom caller) {
// The actual logic goes here.
}
}
public class TheClassYoureCallingFrom {
List<Employee> employees = new ArrayList<Employees>;
public void theMethodYoureCallingFrom() {
for (Employee employee : employees) {
employee.doTheLogic(this);
}
}
}
Of course, if you're not using any of the methods of the calling class, there's no need to pass it as a parameter.
Upvotes: 3
Reputation: 431
You could use Streams:
employees.stream()
.filter(employee -> employee instanceof EmployeeExtender)
.forEach(employee -> {
//do logic
});
Upvotes: 1