如何在foreach循环java

时间:2019-03-11 17:50:47

标签: java oop object foreach return

我试图从for-each循环中获取对象'Employee'的最小值。

我创建了一些员工;

// Create Employees
Employee Employee1 = new Employee(1, "Bradley", 0);
Employee Employee2 = new Employee(2, "Patrick", 0);
Employee Employee3 = new Employee(3, "Erin", 0);
Employee Employee4 = new Employee(4, "Jim", 0);
Employee Employee5 = new Employee(5, "Fredrick", 0);

第三个参数是已分配合同的数量,默认情况下为0。然后,我的代码分配了一些合同,分配的合同数量增加了,等等。然后我像上面的雇员一样创建了一个数组;

Employee[] employees = new Employee[] {Employee1, Employee2, Employee3, Employee4, Employee5};

我可以使用下面的循环打印分配给每位员工的合同数量;

for (Employee employee : employees) {
    System.out.println(employee.numberOfCurrentlyAssignedContracts);
}

我正在尝试返回employee.numberOfCurrentlyAssignedContracts数量最少的雇员,但是我不想返回它的int值,而是希望整个雇员对象都返回,因此我可以在上面调用一个单独的函数,例如:

雇员(已分配合同的值最小).assignContract-将新合同分配给当前分配合同数最少的雇员。因此,基本上,我该如何让每个人返回雇员而不是分配合同的int值?

任何帮助都将受到感激。

关于, B


所有三个提交的答案都有效时该怎么办?谢谢。另外,如果2+的最小值相同,那么我该如何随机退还一名员工,例如2名员工都分配了0个合同。

3 个答案:

答案 0 :(得分:3)

您可以使用一个简单的for循环来查找合同数量最少的员工,如下所示:

int minContract = Integer.MAX_VALUE;
Employee empMin = null;
for (Employee employee : employees) {
    if (employee.getNumberOfCurrentlyAssignedContracts() < minContract) {
        // swap min and employee if true
        empMin = employee;
        minContract = empMin.getNumberOfCurrentlyAssignedContracts();
    }
}

现在,您具有最小合同的雇员对象的引用:

System.out.println(empMin);

如果您使用的是Java-8,则只需执行以下操作即可:

Employee empMin = Arrays.stream(employees)
                        .min((e1, e2) -> 
                                  e1.getNumberOfCurrentlyAssignedContracts() - 
                                  e2.getNumberOfCurrentlyAssignedContracts())
                        .get();

答案 1 :(得分:1)

怎么样:

Employee minEmployee = Arrays.stream(employees)
      .sorted(Comparator.comparing(Employee::getNumberOfCurrentlyAssignedContracts))
      .findFirst().get();

答案 2 :(得分:1)

您可以这样做

Employee ref = employees[0];
int min = ref.numberOfCurrentlyAssignedContracts;
for (Employee employee : employees) {
    if(min>employee.numberOfCurrentlyAssignedContracts){
         min = employee.numberOfCurrentlyAssignedContracts;
         ref = employee;
    }
}

然后用ref做您想做的事

当然,改用ArrayList会容易得多