如何在不使用 for 循环或迭代器的情况下从一组员工中按 ID 查找员工记录?

How do you find the employee record by id from a Set of Employees without using the for loops or iterator?

示例:

Employee Record
1, Paul, 100
2, Peter, 200
3, Riana, 100

按部门 ID 搜索 - 显示 100 个

1, Paul,100 3, Riana,100

注:

  1. 员工记录存储在Set中是为了避免员工id重复。
  2. 尝试仅使用 getter 和 setter 来检索员工记录,而不是遍历员工
  3. 构建器模式用于构建员工记录。

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);
}
}