首页 > 代码库 > Java 8 新特性:4-断言(Predicate)接口

Java 8 新特性:4-断言(Predicate)接口

(原)

这个接口主要用于判断,先看看它的实现,说明,再给个例子。

/*
 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package java.util.function;

import java.util.Objects;

/**
 * Represents a predicate (boolean-valued function) of one argument.
 * 根据一个参数代表了一个基于boolean类型的断言
 * <p>This is a <a href="http://www.mamicode.com/package-summary.html">functional interface</a>
 * whose functional method is {@link #test(Object)}.
 *这是一个函数式接口,它的函数方法是test
 * @param <T> the type of the input to the predicate
 *根据输入类型得到一个断言
 * @since 1.8
 */
@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *根据给定的参数获得判断的结果
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    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.
     * 通过这个predicate和它的参数predicate 返回一个逻辑与的判断结果,
 *当去计算这个复合的predicate时,如果当前的predicate 结果是false,那么就不会计算它的参数other的值。
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *如果这二个其中任何一个抛出异常,具体的处理交给调用的人,如果抛出了异常,它将不会被执行。
     * @param other a predicate that will be logically-ANDed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * AND of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    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.
     * 返回一个predicate 代表了这个predicate的逻辑非
     * @return 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.
     *通过这个predicate和它的参数predicate 返回一个逻辑或的判断结果,
当计算这个组合的predicate,如果这个predicate是true ,那么它的参数other将不会计算
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *如果这二个其中任何一个抛出异常,具体的处理交给调用的人,如果抛出了异常,它将不会被执行。
     * @param other a predicate that will be logically-ORed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * OR of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    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)}.
     *如果二个参数机等的话,根据Objects#equals(Object, Object)返回一个断言的结果
     * @param <T> the type of arguments to the predicate
     * @param targetRef the object reference with which to compare for equality,
     *               which may be {@code null}
     * @return 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);
    }
}

  

这里其实慢慢看它的doc文档,还真没有直接看它的实现来的快。无非就是一个判断的函数式接口,主要做逻辑与或非的判断,其中还有一个静态方法,其实现是这样的:

 

return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);

 

  

null == targetRef这个就不说了,因为它的返回结果是predicate,所以Objects::isNull必需是predicate的实例,它代表了一个方法的引用,为什么它符合这个函数式接口的唯一抽象方法boolean test(T t);这个呢?我们进去看下它的实现。

 

public static boolean isNull(Object obj) {
        return obj == null;
} 

这是一个静态的方法引用,接收一个Object类型的参数,返回一个boolean类型,这完全附合这个函数式接口的boolean test(T t);抽象方法,那么编译器就会认为它是predicate这个函数式接口的一个实现。

 

下面给出一个例子,看下怎么使用的,结果我就不分析了。

package com.demo.jdk8;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Test4 {

	public static void main(String[] args) {
		Predicate<String> p = s -> s.length() > 3;
		
		System.out.println(p.test("hello"));
		
		List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8);
		System.out.println("part1------------------");
		findOdd(list);
		System.out.println("part2------------------");
		conditionFilter(list, ppp -> ppp % 2 == 1);
		System.out.println("part3------------------");
		and(list, p1 -> p1 > 3, p2 -> p2 < 7);
		System.out.println("part4------------------");
		or(list,  p1 -> p1 > 3, p2 -> p2 % 2 == 1);
		System.out.println("part5------------------");
		negate(list, p1 -> p1 > 3);
		System.out.println("part6------------------");
		System.out.println(isEqual("abc").test("abcd"));
		
	}
	
	//找到集合中的奇数
	public static void findOdd(List<Integer> list){
		for (int i = 0; i < list.size(); i++) {
			if(list.get(i) % 2 == 1){
				System.out.println(list.get(i));
			}
		}
	}
	
	public static void conditionFilter(List<Integer> list,Predicate<Integer> p){
		for (int i = 0; i < list.size(); i++) {
			if(p.test(list.get(i))){
				System.out.println(list.get(i));
			}
		}
	}
	
	public static void and(List<Integer> list,Predicate<Integer> p1,Predicate<Integer> p2){
		for (int i = 0; i < list.size(); i++) {
			if(p1.and(p2).test(list.get(i))){
				System.out.println(list.get(i));
			}
		}
	}
	
	public static void or(List<Integer> list,Predicate<Integer> p1,Predicate<Integer> p2){
		for (int i = 0; i < list.size(); i++) {
			if(p1.or(p2).test(list.get(i))){
				System.out.println(list.get(i));
			}
		}
	}
	
	public static void negate(List<Integer> list,Predicate<Integer> p1){
		for (int i = 0; i < list.size(); i++) {
			if(p1.negate().test(list.get(i))){
				System.out.println(list.get(i));
			}
		}
	}
	
	public static Predicate isEqual(Object obj){
		return Predicate.isEqual(obj);
	}
}

  

 

Java 8 新特性:4-断言(Predicate)接口