java8(一)Lambda 使用例子(四步走)

第一步行爲參數化

一般我們傳參數是傳值、引用。但這裏我們要傳行爲。

舉例子: if(XXXXX)   通過參數把判斷的行爲傳進XXXXX 就是行爲參數化,我們可以傳(i>19)等條件

第二步使用函數式接口來傳遞行爲

這裏我直接使用jdk中的接口


 */
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);

    /**
   
}

其實後面還有很多默認接口,但這裏我們關心的是不是默認接口。記住 Lambda 只能用於函數式接口

那什麼是函數式接口?首先一般函數式接口會有註解

@FunctionalInterface

這說明這個接口是函數式接口。

另外最重要的是 接口中只有一個方法定義,除了默認實現的。

這個接口就是有一個test(T t)  來看看   需要傳遞 T 和返回boolean

那Lambda的簽名就應該是   (T t)->boolean

第三步執行一個行爲

public static <T>  List<T> full(List<T> list, Predicate<T> p){
        List<T> results = new ArrayList<>();
        for(T s:list){
            if(p.test(s)){
                results.add(s);
            }
        }
        return results;
    }

至於List<T>  前面爲什麼有<T>可以看我上一篇博客。

行爲就在 p.test(s)體現了

第四步傳遞Lambda

  List<String> s=full(strings,(String string)->!string.isEmpty());

簽名是這個沒錯(T t)->boolean    

(String string)->!string.isEmpty()返回的確實是boolean

 

最後看下例子

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

public class mian1 {



    public static void main(String[] args) {

    List<String> strings=new ArrayList<>();
    strings.add("1");
    strings.add("");
    strings.add("1");

    List<String> s=full(strings,(String string)->!string.isEmpty());
        System.out.println(s);
    }

    public static <T>  List<T> full(List<T> list, Predicate<T> p){
        List<T> results = new ArrayList<>();
        for(T s:list){
            if(p.test(s)){
                results.add(s);
            }
        }
        return results;
    }


}

 

執行結果

[1, 1]

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