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)体现了

扫描二维码关注公众号,回复: 11002704 查看本文章

第四步传递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]

发布了82 篇原创文章 · 获赞 49 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/xu505928168/article/details/97796677