
本文旨在讲解如何利用Java Stream API和函数式接口,对集合数据进行多重条件过滤。我们将探讨如何有效地组合多个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接口提供了and、or和negate等方法,用于实现逻辑与、逻辑或和逻辑非操作。
要实现所有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
}
}要实现只要有一个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
}
}要实现对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进行逻辑与操作:
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。
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
}
}本文介绍了如何使用Java Stream API和Predicate接口,对集合数据进行多重条件过滤。通过组合多个Predicate,可以实现复杂的过滤逻辑,提高代码的灵活性和可维护性。掌握这些技巧,可以编写出更加简洁高效的过滤代码。
以上就是使用Java Stream Filter实现多个函数式接口过滤的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号