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

本文旨在讲解如何利用Java Stream API和函数式接口,对集合数据进行多重条件过滤。我们将探讨如何有效地组合多个Predicate,实现“与”、“或”、“非”等逻辑运算,并提供多种实现方案,帮助你编写简洁高效的过滤代码。
理解函数式接口 Predicate
在Java中,Predicate
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学习网公众号了解相关技术文章。
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
163 收藏
-
312 收藏
-
186 收藏
-
208 收藏
-
136 收藏
-
276 收藏
-
235 收藏
-
401 收藏
-
434 收藏
-
359 收藏
-
367 收藏
-
377 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习