Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 基于Integerlist筛选对象列表_Java_Java 8_Java Stream - Fatal编程技术网

Java 基于Integerlist筛选对象列表

Java 基于Integerlist筛选对象列表,java,java-8,java-stream,Java,Java 8,Java Stream,我有一门课 class Employee String id String name 我想根据deptId列表筛选出员工列表,deptId列表是一个整数列表 Employee emp1 = new Employee("1","Ally"); Employee emp2 = new Employee("2","Billy"); ArrayList<Employee> employeeList =

我有一门课

class Employee
  String id
  String name
我想根据deptId列表筛选出员工列表,deptId列表是一个整数列表

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);
emp1=新员工(“1”、“联盟”);
员工emp2=新员工(“2”,“比利”);
ArrayList employeeList=Arrays.asList(emp1,emp2);
ArrayList ID=Arrays.asList(2);
我写的是

List<Employee> filteredList = employeeList.stream()
  .filter(employee -> ids.contains(employee.getId()))
  .collect(Collectors.toList());
List filteredList=employeeList.stream()
.filter(employee->id.contains(employee.getId()))
.collect(Collectors.toList());

但是作为一个输出,我得到一个空数组。

首先,您需要将
subscription
更改为
employee

将您的ID列表更改为
字符串列表
并相应填充,或者执行以下操作:

List<Employee> filteredList;
filteredList = employeeList.stream()
     .filter(employee -> ids.contains(Integer.parseInt(employee.getId())))
     .collect(Collectors.toList());
列表过滤器列表;
filteredList=employeeList.stream()
.filter(employee->ids.contains(Integer.parseInt(employee.getId()))
.collect(Collectors.toList());

其他选项包括将
Employee
类更改为使用
int
作为id。

这是因为您的员工id是
字符串而不是
int
。此外,我建议将
id
列表转换为
集合。广泛使用的
Set
接口的
HashSet
实现具有更好的查找时间复杂性(O(1)而不是O(n))。
Integer.toString(employee.getId())
String.valueOf(employee.getId())
?太好了,谢谢!我一定还在睡觉,因为我刚刚意识到过滤器中的lambda不正确<代码>订阅
应为员工