gpt4 book ai didi

java - 我需要从 Farm 类的 Employee 类中获取最大值

转载 作者:行者123 更新时间:2023-11-30 01:55:44 24 4
gpt4 key购买 nike

我需要查找并显示农场中工资最高的员工。 这就是我到目前为止所得到的

public class Employee implements Comparable<Employee> {
private String name;
private Integer salary;

public Employee (String name , Integer salary) {
this.name = name;
this.salary = salary;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public Integer getSalary() {
return salary;
}
public String toString() {
return name + " " + salary;
}
public int compareTo(Employee emp) {
return this.salary.compareTo(emp.getSalary());
}

}

员工类别

public class Farm {
private String name;
private Integer surface;

List<Employee> emp = new ArrayList<Employee>();


public Farm(String name , Integer surface) {
this.name = name;
this.surface = surface;
}
public void setName(String name) {
this.name = name;

}
public String getName() {
return name;
}
public void setSurface(Integer surface) {
this.surface = surface;
}
public int getSurface () {
return surface;
}
public String toString() {
return name + " " + surface;
}
public void makeList(String ename , Integer esalary) {
this.emp.add(new Employee(ename,esalary));
}
public void getList() {
for(Employee el : emp)
System.out.println(el);
}

}

最后一个是主要的。问题是我不知道如何才能拥有更多农场并从每一个农场中获得最大 yield 。你们能帮我吗?

这是我的主应用

public class Mainapp {
public static void main(String args[])
{
List <Farm> FarmList = new ArrayList<Farm>();
FarmList.add(new Farm("unirea pizdii", 890030));
FarmList.add(new Farm("pseudo autsm",78594));
FarmList.add(new Farm("haha hihi",854856099));

Farm farm1 = new Farm("Tiguana" , 700);
farm1.makeList("Mihai", 30000);
farm1.makeList("Vladimir", 4000);
farm1.makeList("Tusnic", 3000);
farm1.getList();


Employee emp1 = new Employee(" mihai", 3000);
System.out.println(emp1);
}

}

最佳答案

要为每个农场获取最高工资的员工,您可以使用流 API:

import static java.util.stream.Collectors.*;

Map<Farm, Optional<Employee>> collect =
farmList.stream().collect(groupingBy(Function.identity(),
flatMapping(farm -> farm.getEmployes().stream(),
maxBy(Employee::compareTo))));

结果映射以Farm为键,以Employee以最高工资为值

注意:flatMapping方法来自java9

关于java - 我需要从 Farm 类的 Employee 类中获取最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54609108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com