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

问题描述

示例:

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

按部门 ID 搜索 - 100 个显示

1,100 3,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);
}
}