【Java基础】Java8 使用 stream().filter()过滤List对象(查找符合条件的对象集合)

本篇主要说明在Java8及以上版本中,使用stream().filter()来过滤List对象,查找符合条件的集合。

一、集合对象定义

集合对象以学生类(Student)为例,有学生的基本信息,包括:姓名,性别,年龄,身高,生日几项。

我的学生类代码如下:

package com.iot.productmanual.controller;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDate;
import java.util.List;

/**
 * <p>Student此类用于:学生信息实体 </p>
 * <p>@author:hujm</p>
 * <p>@date:2023年01月12日 18:36</p>
 * <p>@remark:注意此处加了Lombok的@Data、@AllArgsConstructor、@NoArgsConstructor注解,所以此类的Getter/Setter/toString/全参构造/无参构造都省略 </p>
 */
@Data
@ApiModel(value = "学生信息实体")
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Comparable<Student> {

    @ApiModelProperty("姓名")
    private String name;

    @ApiModelProperty("性别 true男 false女")
    private Boolean sex;

    @ApiModelProperty("年龄")
    private Integer age;

    @ApiModelProperty("身高,单位米")
    private Double height;

    @ApiModelProperty("出生日期")
    private LocalDate birthday;

    @Override
    public int compareTo(Student student) {
        return this.age.compareTo(student.getAge());
    }

    @Override
    public String toString() {
        return String.format("%s\t\t%s\t\t%s\t\t%s\t\t%s",
                this.name, this.sex.toString(), this.age.toString(), this.height.toString(), birthday.toString());
    }

    /**
     * 打印学生信息的静态方法
     *
     * @param studentList 学生信息列表
     */
    public static void printStudentList(List<Student> studentList) {
        System.out.println("【姓名】\t【性别】\t【年龄】\t\t【身高】\t\t【生日】");
        System.out.println("-----------------------------------------------------");
        studentList.forEach(s -> System.out.println(s.toString()));
        System.out.println(" ");
    }
}

二、添加测试数据

下面来添加一些测试用的数据,代码如下:

List<Student> studentList = new ArrayList<>();
// 添加测试数据,请不要纠结数据的严谨性
studentList.add(new Student("张三", true, 18, 1.75, LocalDate.of(2005, 3, 26)));
studentList.add(new Student("李四", false, 16, 1.67, LocalDate.of(2007, 8, 30)));
studentList.add(new Student("王五", true, 23, 1.89, LocalDate.of(2000, 1, 16)));
studentList.add(new Student("麻六", false, 27, 1.75, LocalDate.of(1996, 9, 20)));
studentList.add(new Student("刘七", false, 30, 1.93, LocalDate.of(1993, 6, 19)));
studentList.add(new Student("王八", false, 30, 1.75, LocalDate.of(1993, 6, 19)));

三、使用filter()过滤List

添加过滤条件,比如年龄小于25岁并且身高大于1米7的学生列表

// 输出没有过滤条件的学生列表
Student.printStudentList(studentList);
// 添加过滤条件,比如年龄小于25岁并且身高大于1米7的学生列表
List<Student> ageHeightList = studentList.stream().filter(student -> student.getAge() < 25 && student.getHeight() > 1.7).collect(Collectors.toList());
// 输出符合条件的学生列表
Student.printStudentList(ageHeightList);

结果如下图:

本文首发于CSDN,为博主原创文章,如果需要转载,请注明出处,谢谢!

本文完结!

猜你喜欢

转载自blog.csdn.net/weixin_44299027/article/details/128681046