用stream筛选出员工集合中年龄大于25的员工并根据年龄降序排序?

  • Post author:
  • Post category:其他


Staff.java
package cn.zxj.stream;

/**
 * @author: Administrator
 * @since: 2023/4/11 22:50
 * @description:
 */
public class Staff {

    private String name;

    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Staff(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Staff{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
StreamDemo.java
package cn.zxj.stream;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: Administrator
 * @since: 2023/4/11 22:51
 * @description:
 */
public class StreamDemo {

    public static void main(String[] args) {
        //添加员工
        Staff xiaowang = new Staff("xiaowang", 30);
        Staff xiaoli = new Staff("xiaoli", 22);
        Staff xiaozhou = new Staff("xiaozhou", 26);
        ArrayList<Staff> staffs = new ArrayList<>();
        staffs.add(xiaowang);
        staffs.add(xiaoli);
        staffs.add(xiaozhou);

        //过滤出25岁以上的员工,并按年龄降序
        List<Staff> staffResult = staffs.stream().filter(st -> st.getAge() > 25).sorted(Comparator.comparing(Staff::getAge).reversed()).collect(Collectors.toList());
        staffResult.forEach(st-> System.out.println(st.getName()+":"+st.getAge()));

    }
}



版权声明:本文为qq_37325859原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。