问题
I have a class like
class Employee
String id
String name
I want to filter out the list of employees based on the list of deptId which is an integer list
Employee emp1 = new Employee("1","Ally");
Employee emp2 = new Employee("2","Billy");
ArrayList<Employee> employeeList = Arrays.asList(emp1,emp2);
ArrayList<Integer> ids = Arrays.asList(2);
What I have written is
List<Employee> filteredList = employeeList.stream()
.filter(employee -> ids.contains(employee.getId()))
.collect(Collectors.toList());
But as an output I get an empty array.
回答1:
First, you need to change subscription
to employee
.
Either change your ID list to a list of Strings
and populate accordingly or do something like this:
List<Employee> filteredList;
filteredList = employeeList.stream()
.filter(employee -> ids.contains(Integer.parseInt(employee.getId())))
.collect(Collectors.toList());
Other options include changing your Employee
class to use an int
as an id.
来源:https://stackoverflow.com/questions/64877285/filter-an-object-list-based-on-integerlist