源码:

/**
 * 表示一个参数的谓词(布尔值函数)
 * 一个参数, 返回 是否满足函数式的 布尔值
 */
@FunctionalInterface
public interface Predicate<T> {
	// 根据给定参数评估为 布尔值。 
    boolean test(T t);
}

使用:

  /**
   * boolean test(T t);
   * <p>
   * 查看是否满足给定的表达式
   *
   * @return 满足 true 不满足 false
   */
    boolean predicateTest(int i, Predicate<Integer> predicate) {
        return predicate.test(i);
    }
    @Data
    class User {
        Integer id;
    }

使用场景:

    // 查看传入的 值 1 , 是否满足 x > 0 这个函数表达式
    boolean boo = predicateTest(1, (x) -> x > 0);
    // 过滤
    List<User> list = Arrays.asList();
    list.add(User.builder()
            .id(1)
            .build());
    list.add(User.builder()
            .id(2)
            .build());
    List<User> collect = list.stream()
            .filter(x -> x.getId() == 1)
            .collect(Collectors.toList());

看下这里的 filter 源码:

public interface Stream<T> extends BaseStream<T, Stream<T>> {
	// 使用的就是Predicate
	Stream<T> filter(Predicate<? super T> predicate);
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐