要求是流式传输一组对象,根据某些条件进行过滤,并仅收集一组字符串中的员工 ID
class Employee {
private String empId;
private int type;
public int getType() {
return type;
}
public String getEmpId() {
return empId;
}
}
同时过滤下面的语句
employees.stream().filter(x-> x.getType() == 1).collect(Collectors.toSet());
返回 Set<Employee>
相反,我只想收集 empId 即 Set<String>
注意:不能将实例变量设为私有(private)以外的任何内容。
最佳答案
使用 map()
将 Employee
实例映射到相应的 Employee ID。
Set<String> empIds =
employees.stream()
.filter(x-> x.getType() == 1)
.map(Employee::getEmpId)
.collect(Collectors.toSet());
关于java - 如何流式传输和收集对象集合的实例方法结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55514620/