Java list stream().filter()按条件过滤查找对象

java | 2020-07-13 14:55:40

利用Java8新特性,使用stream().filter()来过滤一个List对象,查找符合条件的对象集合。

1.list里面的学生对象

public class StudentInfo implements Comparable<StudentInfo> {

    //名称
    private String name;

    //性别 true男 false女
    private Boolean gender;

    //年龄
    private Integer age;

    //身高
    private Double height;

    //出生日期
    private LocalDate birthday;

    public StudentInfo(String name, Boolean gender, Integer age, Double height, LocalDate birthday){
        this.name = name;
        this.gender = gender;
        this.age = age;
        this.height = height;
        this.birthday = birthday;
    }

    public String toString(){
        String info = String.format("%s\t\t%s\t\t%s\t\t\t%s\t\t%s",this.name,this.gender.toString(),this.age.toString(),this.height.toString(),birthday.toString());
        return info;
    }

    public static void printStudents(List<StudentInfo> studentInfos){
        System.out.println("[姓名]\t\t[性别]\t\t[年龄]\t\t[身高]\t\t[生日]");
        System.out.println("----------------------------------------------------------");
        studentInfos.forEach(s->System.out.println(s.toString()));
        System.out.println(" ");
    }

    @Override
    public int compareTo(StudentInfo ob) {
        return this.age.compareTo(ob.getAge());
        //return 1;
    }

}

2.测试数据

//测试数据,请不要纠结数据的严谨性
List<StudentInfo> studentList = new ArrayList<>();
studentList.add(new StudentInfo("李小明",true,18,1.76,LocalDate.of(2001,3,23)));
studentList.add(new StudentInfo("张小丽",false,18,1.61,LocalDate.of(2001,6,3)));
studentList.add(new StudentInfo("王大朋",true,19,1.82,LocalDate.of(2000,3,11)));
studentList.add(new StudentInfo("陈小跑",false,17,1.67,LocalDate.of(2002,10,18)));

3.使用filter()过滤List

//查找身高在1.8米及以上的男生
List<StudentInfo> boys = studentList.stream().filter(s->s.getGender() && s.getHeight() >= 1.8).collect(Collectors.toList());
//输出查找结果
StudentInfo.printStudents(boys);

4.输出结果

 

登录后即可回复 登录 | 注册
    
关注编程学问公众号