Java8 de interfaz de predicados

fuente predicado con función de como, podemos comparar estos dos analizados. Predicado directamente en el código fuente:

public interface Predicate<T> {
    /**
     * Evaluates this predicate on the given argument.
     */
    boolean test(T t);

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * AND of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code false}, then the {@code other}
     * predicate is not evaluated.
     */
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    /**
     * Returns a predicate that represents the logical negation of this
     * predicate.
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * OR of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code true}, then the {@code other}
     * predicate is not evaluated.
     */
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    /**
     * Returns a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}.
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

interfaz de predicados se afirma Sus parámetros son <T, boolean>, es decir, a un parámetro T, devolver el resultado del tipo booleano. Función con la misma implementación específica predicado también se basa en la expresión lambda entrante para decidir.

boolean test(T t);

A continuación nos fijamos en Predicado aplicación por defecto de tres maneras y, o y negar importantes

 default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

Estos tres métodos se corresponden con tres símbolos && java la conexión, y ||, uso básico es muy simple, la siguiente dan un aspecto ejemplo !:

int[] numbers= {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
        List<Integer> list=new ArrayList<>();
        for(int i:numbers) {
            list.add(i);
        }
        Predicate<Integer> p1=i->i>5;
        Predicate<Integer> p2=i->i<20;
        Predicate<Integer> p3=i->i%2==0;
        List test=list.stream().filter(p1.and(p2).and(p3)).collect(Collectors.toList());
        System.out.println(test.toString());
/** print:[6, 8, 10, 12, 14]*/

Se definieron tres afirmaciones p1, p2, p3. Ahora hay una lista de 1 ~ 15, tenemos que filtrar esta lista. El filtro descrito anteriormente es para filtrar todas las partículas de más de 5 a menos de 20, y la lista es par.

Si de repente nuestras necesidades cambian, y ahora tenemos que filtrar impar. Así que no puedo ir directamente a cambiar de predicados, debido a que el proyecto real en esta condición también puede que quiera usar en otros lugares. Así que esta vez sólo se necesita cambiar las condiciones de filtro en el predicado.

List test=list.stream().filter(p1.and(p2).and(p3.negate())).collect(Collectors.toList());
/** print:[7, 9, 11, 13, 15]*/

Nos negación directa de p3 esta condición se puede lograr. No es que sea sencillo?

IsEqual tipo de retorno de este método es el predicado, por lo que podemos ponerlo a trabajar como una interfaz funcional. Podemos suponer == operador usar.

 List test=list.stream()
            .filter(p1.and(p2).and(p3.negate()).and(Predicate.isEqual(7)))
            .collect(Collectors.toList());
/** print:[7] */
Publicado 80 artículos originales · ganado elogios 140 · vistas 640 000 +

Supongo que te gusta

Origin blog.csdn.net/linjpg/article/details/102547638
Recomendado
Clasificación