登录
首页 >  文章 >  java教程

JavaStream多条件过滤方法解析

时间:2025-10-24 19:00:36 185浏览 收藏

本文深入解析**Java Stream多条件过滤技巧**,重点讲解如何利用Java 8 Stream API和函数式接口Predicate,高效地对集合数据进行多重条件过滤。我们将详细探讨如何组合多个Predicate,实现灵活的“与”、“或”、“非”等复杂逻辑运算,并提供多种实用的实现方案,助力开发者编写出更简洁、更高效的Java过滤代码。通过学习本文,你将掌握利用Predicate接口和Stream API进行数据筛选的核心技术,提升数据处理能力。无论你是Java初学者还是经验丰富的开发者,都能从中受益,优化你的代码。

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

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

理解函数式接口 Predicate

在Java中,Predicate是一个函数式接口,它接受一个类型为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方法。

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方法。

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,可以实现复杂的过滤逻辑,提高代码的灵活性和可维护性。掌握这些技巧,可以编写出更加简洁高效的过滤代码。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《JavaStream多条件过滤方法解析》文章吧,也可关注golang学习网公众号了解相关技术文章。

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>