如何解决如何在不使用 for 循环或迭代器的情况下从一组员工中按 id 查找员工记录?
示例:
Employee Record
1,Paul,100
2,Peter,200
3,Riana,100
1,100 3,100
注意:
- 员工记录存储在 Set 中,以避免重复员工 ID。
- 尝试仅使用 getter 和 setter 来检索员工记录,而不是遍历员工
- 构建器模式用于构建员工记录。
解决方法
Streams 可用于对记录集应用过滤器并获取结果。以下是根据departmentId 的搜索条件显示员工详细信息的示例代码。
import java.util.*;
import java.util.stream.Collectors;
class EmployeeDetails {
int employeeId;
String name;
int departmentId;
public EmployeeDetails(int employeeId,String name,int departmentId) {
this.employeeId = employeeId;
this.name = name;
this.departmentId = departmentId;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDepartmentId() {
return departmentId;
}
public void setDepartmentId(int departmentId) {
this.departmentId = departmentId;
}
@Override
public String toString() {
return "EmployeeDetails{" +
"employeeId=" + employeeId +
",name='" + name + '\'' +
",departmentId=" + departmentId +
'}';
}
}
public class Employee{
public static void main(String[] args){
EmployeeDetails employee1 = new EmployeeDetails(1,"Paul",100);
EmployeeDetails employee2 = new EmployeeDetails(2,"Peter",200);
EmployeeDetails employee3 = new EmployeeDetails(3,"Raina",100);
Set<EmployeeDetails> employees = new HashSet<>();
employees.add(employee1);
employees.add(employee2);
employees.add(employee3);
int filteredDepartmentId = 100;
employees.stream()
.filter(e -> Integer.compare(filteredDepartmentId,e.getDepartmentId()) == 0)
.forEach(System.out::println);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。