java.util.function
包中的 Predicate<T>
接口是 Java 8 引入的函数式接口之一,用于表示一个参数的谓词(布尔值函数)。Predicate
接口主要用于定义对某个类型 T
的对象进行条件测试的逻辑,并返回一个布尔值(true
或 false
)。
Predicate
接口的主要用途包括:
- 条件过滤:在集合(如
List
、Set
)中过滤出满足特定条件的元素。 - 逻辑判断:在业务逻辑中用于判断某个对象是否满足某个条件。
- 组合条件:通过
Predicate
接口提供的默认方法(如and
、or
、negate
),可以将多个Predicate
组合在一起,形成更复杂的条件判断。
Predicate
接口的主要方法包括:
boolean test(T t)
:用于测试指定的输入参数是否满足此谓词的条件。default Predicate<T> and(Predicate<? super T> other)
:返回一个组合谓词,该谓词接受两个输入谓词作为参数,仅当两个谓词都为true
时返回true
。default Predicate<T> or(Predicate<? super T> other)
:返回一个组合谓词,该谓词接受两个输入谓词作为参数,只要其中一个谓词为true
,就返回true
。default Predicate<T> negate()
:返回一个表示否定(逻辑非)的谓词。static <T> Predicate<T> isEqual(Object targetRef)
:返回一个谓词,该谓词测试输入是否等于指定的目标引用。static <T> Predicate<T> not(Predicate<? super T> target)
:返回一个表示目标谓词的逻辑否定的谓词。
代码示例:
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PredicateExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
// 定义一个Predicate来检查字符串长度是否大于4
Predicate<String> lengthPredicate = name -> name.length() > 4;
// 使用Stream API进行过滤
List<String> filteredNames = names.stream()
.filter(lengthPredicate)
.collect(Collectors.toList());
System.out.println(filteredNames); // 输出: [Alice, Charlie, David]
// 使用组合条件
Predicate<String> startsWithA = name -> name.startsWith("A");
Predicate<String> combinedPredicate = startsWithA.and(lengthPredicate);
List<String> combinedFilteredNames = names.stream()
.filter(combinedPredicate)
.collect(Collectors.toList());
System.out.println(combinedFilteredNames); // 输出: [Alice]
}
}
运行结果:
[Alice, Charlie, David]
[Alice]