Java 8 in action代碼總結 1 - filter

調用filter方法過濾目標集合

//調用filter的代碼
//filter方法中ApplePredicate接口當作參數傳入,
//在調用filter方法的時候則需要傳入這個接口的具體實現,對應接口內的方法也要重寫;具體的過濾也在filter重寫方法的內部實現
List<Apple> apples = filter(inventory, new ApplePredicate() {
	@Override
	public boolean test(Apple a) {
		return a.getWeight() > 119;
	}
});
System.out.println(apples);

自定義的Predicate接口 和 filter方法

  • 自定義Predicate接口的抽象方法的參數爲最後具體要過濾和比較的對象
  • filter方法的參數是Predicate接口,以及需要過濾的集合或者數組
public static List<Apple> filter(List<Apple> inventory, ApplePredicate p){
	List<Apple> result = new ArrayList<>();
	for(Apple apple : inventory){
		if(p.test(apple)){
			result.add(apple);
		}
	}
	return result;
}   

interface ApplePredicate{
	public boolean test(Apple a);
}   

總結:這邊接口作爲參數,是行爲參數化的體現,是java8 in action中chapter 2的主題 - Passing code with behavior parameterization

JDK8自帶的Predicate(謂詞)接口

jdk8自帶的Predicate接口,用來代替上面的自定義的謂詞接口。
該接口中定義了test,negate,or ,and,isEqual等方法。
當調用這個接口的時候,我們需要先定義一個filter()方法,傳入Collection操作對象,根據所要做的操作,傳入適當個數的Predicate作爲參數。

調用代碼

List<Apple> greenApples = filterApples(inventory, FilteringApples::isGreenApple);
System.out.println(greenApples);

List<Apple> greenApples2 = filterApples(inventory, (Apple a) -> "green".equals(a.getColor()));
System.out.println(greenApples2);

自定義filter方法

public static boolean isGreenApple(Apple apple) {
 	return "green".equals(apple.getColor()); 
}

public static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> p){
	List<Apple> result = new ArrayList<>();
  	for(Apple apple : inventory){
  	 	//取反
      	Predicate<Apple> negate = p.negate();
      	//取反靜態方法
      	Predicate<Apple> not = Predicate.not(p);
      	if(negate.test(apple)){
          result.add(apple);
      	}
  	}
  	return result;
}

public static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> p,Predicate<Apple> p1){
    List<Apple> result = new ArrayList<>();
    for(Apple apple : inventory){
    	//二合一
        Predicate<Apple> and = p.and(p1);
        //二選一
        Predicate<Apple> or = p.or(p1);
        if(and.test(apple)){
            result.add(apple);
        }
    }
    return result;
}

Predicate接口代碼

package java.util.function;
import java.util.Objects;

/**
 * Represents a predicate (boolean-valued function) of one argument.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #test(Object)}.
 *
 * @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.
     * 返回合併兩個謂詞邏輯的新的謂詞
     *
     * <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.
     * 返回一個與給定代碼邏輯相反的謂詞,取反
     *
     * @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.
     * 返回一個符合兩個中的一個謂詞的新的謂詞
     *
     * <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)}.
     * 判斷兩個謂詞的效果是否一樣
     *
     * @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);
    }

    /**
     * Returns a predicate that is the negation of the supplied predicate.
     * This is accomplished by returning result of the calling
     * 靜態方法,和negate效果一樣
     * {@code target.negate()}.
     *
     * @param <T>     the type of arguments to the specified predicate
     * @param target  predicate to negate
     *
     * @return a predicate that negates the results of the supplied
     *         predicate
     *
     * @throws NullPointerException if target is null
     *
     * @since 11
     */
    @SuppressWarnings("unchecked")
    static <T> Predicate<T> not(Predicate<? super T> target) {
        Objects.requireNonNull(target);
        return (Predicate<T>)target.negate();
    }
}

總結:需要自定義的兩段代碼邏輯

  • 一是調用謂詞的filter方法
    在這裏插入圖片描述

  • 二是謂詞部分傳入的代碼片段或者方法
    在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章