首页 > Java > java教程 > 正文

使用Java Stream Filter实现多个函数式接口过滤

DDD
发布: 2025-10-12 11:43:35
原创
216人浏览过

使用java stream filter实现多个函数式接口过滤

本文旨在讲解如何利用Java Stream API和函数式接口,对集合数据进行多重条件过滤。我们将探讨如何有效地组合多个Predicate,实现“与”、“或”、“非”等逻辑运算,并提供多种实现方案,帮助你编写简洁高效的过滤代码。

理解函数式接口 Predicate

在Java中,Predicate<T>是一个函数式接口,它接受一个类型为T的参数,并返回一个布尔值。Predicate接口的核心方法是test(T t),用于判断给定的输入是否满足特定条件。 使用Predicate接口可以方便地定义过滤条件,并将其应用于Stream API的filter操作中。

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.function.Predicate;

import lombok.Getter;

class Student {
  @Getter private LocalDate birthDate;

  public Student(LocalDate birthDate) {
        this.birthDate = birthDate;
  }
}

public class PredicateExample {

    public static void main(String[] args) {
        Predicate<Student> isAdult = s -> ChronoUnit.YEARS.between(
          LocalDate.now(), s.getBirthDate()) >= 18;

        Student student1 = new Student(LocalDate.now().minusYears(20));
        Student student2 = new Student(LocalDate.now().minusYears(16));

        System.out.println("Student 1 is adult: " + isAdult.test(student1)); // Output: true
        System.out.println("Student 2 is adult: " + isAdult.test(student2)); // Output: false
    }
}
登录后复制

组合多个 Predicate

当需要应用多个过滤条件时,可以将多个Predicate组合起来。Predicate接口提供了and、or和negate等方法,用于实现逻辑与、逻辑或和逻辑非操作。

1. 逻辑与 (AND)

要实现所有Predicate都满足时才保留元素,可以使用and方法。

立即学习Java免费学习笔记(深入)”;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import lombok.Getter;

class Student {
    @Getter private LocalDate birthDate;
    @Getter private String name;

    public Student(LocalDate birthDate, String name) {
        this.birthDate = birthDate;
        this.name = name;
    }
}

public class AndPredicateExample {

    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
            new Student(LocalDate.now().minusYears(20), "Alice"),
            new Student(LocalDate.now().minusYears(16), "Bob"),
            new Student(LocalDate.now().minusYears(22), "Charlie")
        );

        Predicate<Student> isAdult = s -> ChronoUnit.YEARS.between(LocalDate.now(), s.getBirthDate()) >= 18;
        Predicate<Student> nameStartsWithA = s -> s.getName().startsWith("A");

        // 使用 and 方法组合 Predicate
        Predicate<Student> combinedPredicate = isAdult.and(nameStartsWithA);

        // 使用 Stream API 进行过滤
        List<Student> filteredStudents = students.stream()
            .filter(combinedPredicate)
            .collect(Collectors.toList());

        filteredStudents.forEach(student -> System.out.println(student.getName())); // Output: Alice
    }
}
登录后复制

2. 逻辑或 (OR)

要实现只要有一个Predicate满足就保留元素,可以使用or方法。

SpeakingPass-打造你的专属雅思口语语料
SpeakingPass-打造你的专属雅思口语语料

使用chatGPT帮你快速备考雅思口语,提升分数

SpeakingPass-打造你的专属雅思口语语料25
查看详情 SpeakingPass-打造你的专属雅思口语语料
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import lombok.Getter;

class Student {
    @Getter private LocalDate birthDate;
    @Getter private String name;

    public Student(LocalDate birthDate, String name) {
        this.birthDate = birthDate;
        this.name = name;
    }
}

public class OrPredicateExample {

    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
            new Student(LocalDate.now().minusYears(20), "Alice"),
            new Student(LocalDate.now().minusYears(16), "Bob"),
            new Student(LocalDate.now().minusYears(22), "Charlie")
        );

        Predicate<Student> isAdult = s -> ChronoUnit.YEARS.between(LocalDate.now(), s.getBirthDate()) >= 18;
        Predicate<Student> nameStartsWithB = s -> s.getName().startsWith("B");

        // 使用 or 方法组合 Predicate
        Predicate<Student> combinedPredicate = isAdult.or(nameStartsWithB);

        // 使用 Stream API 进行过滤
        List<Student> filteredStudents = students.stream()
            .filter(combinedPredicate)
            .collect(Collectors.toList());

        filteredStudents.forEach(student -> System.out.println(student.getName())); // Output: Alice, Bob, Charlie
    }
}
登录后复制

3. 逻辑非 (NOT)

要实现对Predicate取反,可以使用negate方法。

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import lombok.Getter;

class Student {
    @Getter private LocalDate birthDate;
    @Getter private String name;

    public Student(LocalDate birthDate, String name) {
        this.birthDate = birthDate;
        this.name = name;
    }
}

public class NegatePredicateExample {

    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
            new Student(LocalDate.now().minusYears(20), "Alice"),
            new Student(LocalDate.now().minusYears(16), "Bob"),
            new Student(LocalDate.now().minusYears(22), "Charlie")
        );

        Predicate<Student> isAdult = s -> ChronoUnit.YEARS.between(LocalDate.now(), s.getBirthDate()) >= 18;

        // 使用 negate 方法取反 Predicate
        Predicate<Student> combinedPredicate = isAdult.negate();

        // 使用 Stream API 进行过滤
        List<Student> filteredStudents = students.stream()
            .filter(combinedPredicate)
            .collect(Collectors.toList());

        filteredStudents.forEach(student -> System.out.println(student.getName())); // Output: Bob
    }
}
登录后复制

使用循环组合 Predicate

如果需要动态地组合多个Predicate,可以使用循环来实现。例如,将多个Predicate进行逻辑与操作:

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import lombok.Getter;

class Student {
    @Getter private LocalDate birthDate;
    @Getter private String name;

    public Student(LocalDate birthDate, String name) {
        this.birthDate = birthDate;
        this.name = name;
    }
}

public class LoopPredicateExample {

    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
            new Student(LocalDate.now().minusYears(20), "Alice"),
            new Student(LocalDate.now().minusYears(16), "Bob"),
            new Student(LocalDate.now().minusYears(22), "Charlie")
        );

        List<Predicate<Student>> filters = Arrays.asList(
            s -> ChronoUnit.YEARS.between(LocalDate.now(), s.getBirthDate()) >= 18,
            s -> s.getName().startsWith("A")
        );

        // 使用循环组合 Predicate
        Predicate<Student> combinedPredicate = s -> true;
        for (Predicate<Student> filter : filters) {
            combinedPredicate = combinedPredicate.and(filter);
        }

        // 使用 Stream API 进行过滤
        List<Student> filteredStudents = students.stream()
            .filter(combinedPredicate)
            .collect(Collectors.toList());

        filteredStudents.forEach(student -> System.out.println(student.getName())); // Output: Alice
    }
}
登录后复制

使用 Stream API 的 reduce 操作组合 Predicate

除了循环,还可以使用Stream API的reduce操作来组合Predicate。

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import lombok.Getter;

class Student {
    @Getter private LocalDate birthDate;
    @Getter private String name;

    public Student(LocalDate birthDate, String name) {
        this.birthDate = birthDate;
        this.name = name;
    }
}

public class ReducePredicateExample {

    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
            new Student(LocalDate.now().minusYears(20), "Alice"),
            new Student(LocalDate.now().minusYears(16), "Bob"),
            new Student(LocalDate.now().minusYears(22), "Charlie")
        );

        List<Predicate<Student>> filters = Arrays.asList(
            s -> ChronoUnit.YEARS.between(LocalDate.now(), s.getBirthDate()) >= 18,
            s -> s.getName().startsWith("A")
        );

        // 使用 Stream API 的 reduce 操作组合 Predicate
        Predicate<Student> combinedPredicate = filters.stream()
            .reduce(s -> true, Predicate::and);

        // 使用 Stream API 进行过滤
        List<Student> filteredStudents = students.stream()
            .filter(combinedPredicate)
            .collect(Collectors.toList());

        filteredStudents.forEach(student -> System.out.println(student.getName())); // Output: Alice
    }
}
登录后复制

注意事项

  • 确保Predicate的逻辑清晰,避免出现复杂的嵌套条件。
  • 尽量使用Predicate接口提供的and、or和negate方法,提高代码的可读性。
  • 在处理大量数据时,注意Predicate的性能,避免出现性能瓶颈

总结

本文介绍了如何使用Java Stream API和Predicate接口,对集合数据进行多重条件过滤。通过组合多个Predicate,可以实现复杂的过滤逻辑,提高代码的灵活性和可维护性。掌握这些技巧,可以编写出更加简洁高效的过滤代码。

以上就是使用Java Stream Filter实现多个函数式接口过滤的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号