如何使用java8流在下面的数组列表中找到第二高的薪水

dzhpxtsq  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(413)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

上个月关门了。
改进这个问题

class Employee
{
    int id;

    String name;

    int age;

    String gender;

    String department;

    int yearOfJoining;

    double salary;

    public Employee(int id, String name, int age, String gender, String department, int yearOfJoining, double salary) 
    {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.department = department;
        this.yearOfJoining = yearOfJoining;
        this.salary = salary;
    }

    public int getId() 
    {
        return id;
    }

    public String getName() 
    {
        return name;
    }

    public int getAge() 
    {
        return age;
    }

    public String getGender() 
    {
        return gender;
    }

    public String getDepartment() 
    {
        return department;
    }

    public int getYearOfJoining() 
    {
        return yearOfJoining;
    }

    public double getSalary() 
    {
        return salary;
    }

    @Override
    public String toString() 
    {
        return "Id : "+id
                +", Name : "+name
                +", age : "+age
                +", Gender : "+gender
                +", Department : "+department
                +", Year Of Joining : "+yearOfJoining
                +", Salary : "+salary;
    }
}
List<Employee> employeeList = new ArrayList<Employee>();

employeeList.add(new Employee(111, "Jiya Brein", 32, "Female", "HR", 2011, 25000.0));
employeeList.add(new Employee(122, "Paul Niksui", 25, "Male", "Sales And Marketing", 2015, 13500.0));
employeeList.add(new Employee(133, "Martin Theron", 29, "Male", "Infrastructure", 2012, 18000.0));
employeeList.add(new Employee(144, "Murali Gowda", 28, "Male", "Product Development", 2014, 32500.0));
employeeList.add(new Employee(155, "Nima Roy", 27, "Female", "HR", 2013, 22700.0));

Optional<Employee> emp = employeeList.stream()
        .collect(Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary)));
xxe27gdn

xxe27gdn1#

按薪资的倒序排序后,可以用 skip(1) 然后找第一个员工 findFirst() 找到第二高工资的方法。
试试这个:

Optional<Employee> emp = employeeList.stream()
        .sorted(Comparator.comparingDouble(Employee::getSalary).reversed()).skip(1).findFirst();

System.out.println(emp.get());

输出:

Id : 111, Name : Jiya Brein, age : 32, Gender : Female, Department : HR, Year Of Joining : 2011, Salary : 25000.0
okxuctiv

okxuctiv2#

你需要按清单排序。然后得到2。
employeelist.stream().sorted(comparator.comparingdouble(employee::getsalary)
emp.get(2)

相关问题