Predicate组合条件如何使用

wen java案例 2

本文目录导读:

Predicate组合条件如何使用

  1. Predicate 基本用法
  2. 组合条件:and / or / negate
  3. 实际业务场景:过滤列表
  4. 动态组合多个 Predicate
  5. 使用静态方法 Predicate.isEqual
  6. 注意点
  7. 完整示例:复杂条件查询(模拟)

在 Java 中,Predicatejava.util.function 包下的一个函数式接口,常用于过滤、条件判断等场景,它提供了一些默认方法(如 andornegate)来组合多个条件。

下面从基础用法组合应用逐步说明:


Predicate 基本用法

import java.util.function.Predicate;
public class PredicateDemo {
    public static void main(String[] args) {
        // 定义两个基本条件
        Predicate<Integer> isEven = num -> num % 2 == 0;
        Predicate<Integer> isGreaterThan10 = num -> num > 10;
        System.out.println(isEven.test(8));   // true
        System.out.println(isGreaterThan10.test(15)); // true
    }
}

组合条件:and / or / negate

public class PredicateCombine {
    public static void main(String[] args) {
        Predicate<Integer> isEven = num -> num % 2 == 0;
        Predicate<Integer> isGreaterThan10 = num -> num > 10;
        // and: 既是偶数又大于10
        Predicate<Integer> evenAndGt10 = isEven.and(isGreaterThan10);
        System.out.println(evenAndGt10.test(12)); // true
        System.out.println(evenAndGt10.test(8));  // false
        // or: 是偶数 或 大于10
        Predicate<Integer> evenOrGt10 = isEven.or(isGreaterThan10);
        System.out.println(evenOrGt10.test(8));   // true
        System.out.println(evenOrGt10.test(9));   // false
        // negate: 取反(不是偶数)
        Predicate<Integer> isOdd = isEven.negate();
        System.out.println(isOdd.test(5)); // true
    }
}

实际业务场景:过滤列表

这是最常用的方式,结合 Stream API 使用:

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class FilterDemo {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 5, 8, 12, 15, 20, 23);
        Predicate<Integer> isEven = n -> n % 2 == 0;
        Predicate<Integer> isGt10 = n -> n > 10;
        // 组合:偶数且大于10
        List<Integer> result = numbers.stream()
                .filter(isEven.and(isGt10))
                .collect(Collectors.toList());
        System.out.println(result); // [12, 20]
    }
}

动态组合多个 Predicate

当条件数量不确定时,可以用集合或数组来动态组合:

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class DynamicCombine {
    public static void main(String[] args) {
        List<Predicate<Integer>> conditions = new ArrayList<>();
        conditions.add(n -> n > 5);
        conditions.add(n -> n < 20);
        conditions.add(n -> n % 2 == 0);
        // 合并所有条件(且关系)
        Predicate<Integer> combined = conditions.stream()
                .reduce(Predicate::and)
                .orElse(n -> true); // 如果没有条件,默认全部通过
        System.out.println(combined.test(12)); // true
        System.out.println(combined.test(3));  // false
    }
}

使用静态方法 Predicate.isEqual

用于比较是否等于某个固定值:

Predicate<String> isHello = Predicate.isEqual("Hello");
System.out.println(isHello.test("Hello")); // true
System.out.println(isHello.test("World")); // false

注意点

特性 说明
惰性求值 and()or() 只是返回新的 Predicate,不会立即执行
短路求值 and 中如果第一个条件 false,后续条件不会执行(类似 &&
or 中如果第一个条件 true,后续条件不会执行(类似 )
不可变 原始 Predicate 不会被修改,每次组合都返回新对象

完整示例:复杂条件查询(模拟)

public class UserFilter {
    public static void main(String[] args) {
        List<User> users = Arrays.asList(
            new User("Alice", 25, true),
            new User("Bob", 17, false),
            new User("Charlie", 30, true)
        );
        Predicate<User> adult = u -> u.getAge() >= 18;
        Predicate<User> active = u -> u.isActive();
        Predicate<User> nameStartsWithA = u -> u.getName().startsWith("A");
        // 组合:成年人 且 活跃用户 且(名字以A开头 或 年龄大于30)
        Predicate<User> complex = adult
                .and(active)
                .and(nameStartsWithA.or(u -> u.getAge() > 30));
        List<User> filtered = users.stream()
                .filter(complex)
                .collect(Collectors.toList());
        filtered.forEach(System.out::println);
        // 输出:Alice (25, active)
    }
}

  • 基础组合and()or()negate()
  • 批量组合:用 reduce(Predicate::and)reduce(Predicate::or)
  • 常用场景:Stream 的 filter()Optional.filter()、集合筛选
  • 注意事项:短路求值、惰性求值、不可变性

掌握这些组合方式,可以写出非常灵活、可复用的条件判断逻辑。

抱歉,评论功能暂时关闭!