函数式接口常用默认方法
大约 1 分钟函数式编程函数式接口
and
我们在使用Predicate接口时,需要进行判断条件的拼接。and方法相当于是使用 && 来拼接判断条件。
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
打印作家中年龄大于17并且姓名的长度大于1的作家:
public static void main(String[] args) throws Throwable {
List<Author> authors = getAuthors();
authors.stream()
.filter(((Predicate<Author>) author -> author.getAge() > 17)
.and(author -> author.getName().length() > 1))
.forEach(author -> System.out.println(author));
}
自定义方法使用
public static void main(String[] args) throws Throwable {
printNum(num -> num % 2 == 0, num -> num > 4);
}
public static void printNum(IntPredicate predicate, IntPredicate predicate2){
int[] arr = {1,2,3,4,5,6,7,8,9,10};
for (int i : arr) {
if (predicate.and(predicate2).test(i)){
System.out.println(i);
}
}
}
结果:
6
8
10
Process finished with exit code 0
or
我们在使用Predicate接口时,需要进行判断条件的拼接。and方法相当于是使用 || 来拼接判断条件。
打印作家中年龄大于17或者姓名的长度小于2的作家:
public static void main(String[] args) throws Throwable {
List<Author> authors = getAuthors();
authors.stream()
.filter(((Predicate<Author>) author -> author.getAge() > 17)
.or(author -> author.getName().length() < 2))
.forEach(author -> System.out.println(author));
}
negate
Predicate接口中的方法。negate方法相当于是在判断前面添加了!,表示取反。
打印作家年龄不大于17的作家:
public static void main(String[] args) throws Throwable {
List<Author> authors = getAuthors();
authors.stream()
.filter(((Predicate<Author>) author -> author.getAge() > 17)
.negate())
.forEach(author -> System.out.println(author));
}