Filter an object list based on Integerlist [closed]

有些话、适合烂在心里 提交于 2020-11-30 00:12:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!