项目作者: mtumilowicz

项目描述 :
Java 11 Predicate Interface.
高级语言: Java
项目地址: git://github.com/mtumilowicz/java11-predicate.git
创建时间: 2018-10-09T20:06:32Z
项目社区:https://github.com/mtumilowicz/java11-predicate

开源协议:

下载


Build Status

java11-predicate

The main goal of this project is to show updated Predicate Interface
from Java 11.

overview

  • and: returns a composed predicate that represents a short-circuiting
    logical AND of this predicate and another

    1. default Predicate<T> and(Predicate<? super T> other) {
    2. Objects.requireNonNull(other);
    3. return (t) -> test(t) && other.test(t);
    4. }
  • negate: returns a predicate that represents the logical negation
    of this predicate

    1. default Predicate<T> negate() {
    2. return (t) -> !test(t);
    3. }
  • or: returns a composed predicate that represents a short-circuiting
    logical OR of this predicate and another

    1. default Predicate<T> or(Predicate<? super T> other) {
    2. Objects.requireNonNull(other);
    3. return (t) -> test(t) || other.test(t);
    4. }
  • isEqual: returns a predicate that tests if two arguments are equal
    according to Objects.equals(Object, Object)

    1. static <T> Predicate<T> isEqual(Object targetRef) {
    2. return (null == targetRef)
    3. ? Objects::isNull
    4. : object -> targetRef.equals(object);
    5. }
  • not: returns a predicate that is the negation of the supplied
    predicate

    1. static <T> Predicate<T> not(Predicate<? super T> target) {
    2. Objects.requireNonNull(target);
    3. return (Predicate<T>)target.negate();
    4. }

best practices

Suppose that we want to filter Stream of objects by some field

  1. class X {
  2. String value;
  3. // constructors, getters...
  4. }
  • naive approach
    1. List<X> filtered = xes.stream()
    2. .filter(x -> Objects.equals(x.value, "test"))
    3. .collect(Collectors.toList());
  • better approach
    1. define static method in X
      1. static Predicate<X> byValue(String value) {
      2. return x -> nonNull(x) && Objects.equals(x.value, value);
      3. }
    2. construct pipeline
      1. List<X> filtered = xes.stream()
      2. .filter(X.byValue("test1"))
      3. .collect(Collectors.toList());
    3. easy to compose
      1. var filtered = xes.stream()
      2. .filter(X.byValue("test1").or(X.byValue("test2")))
      3. .collect(Collectors.toList());