java8 lamda

我们实现接口有很多种形式其中一种就是匿名实现类的方式:

我们先定义一个接口 (@FunctionalInterface  函数式接口:接口中只定义一个方法的接口称之为函数是接口)

@FunctionalInterface
public interface InterfaceLamdaFunction1 {
    int get(Integer t);
}

实现接口

    @Test
    public void e() {
        /*匿名内部类实现*/
        InterfaceLamdaFunction1 function1 =new InterfaceLamdaFunction1() {
            @Override
            public void get(Integer t) {
                return t;
            }
        };
    }

lambda实现方式

lambda表达式可以看作是简化了匿名内部类实现

    @Test
    public void g() {
        InterfaceLamdaFunction1 function1 = (Integer x) -> {return x;};
    }

当前表达式  (Integer x) -> {return x;};    是对InterfaceLamdaFunction1  接口的实现 其中  (Integer x) 是接口中get方法的参数列表 右侧是 {return x;}; 对get方法的 @Override。

lambda 的语法

 (Integer x) -> {return x;};  其中 -> 左侧为 方法参数列表 右侧为方法体。

左侧的类型可以省略  (x) -> {return x;};

右侧方法体如果只有一行代码 {} 和 return 也可以省略  (x) -> x; 

 java.util.function 包中定义了很多函数式接口

其中有四个基本的函数式接口

1.消费型接口: Consumer<T>  : void accept(T t)
2.供给型接口: Supplier<T>  : T get()
3.函数型接口: Function<T,R> : R apply(T t)
4.断定型接口: Predicate<T>  : boolean test(T t)

简单使用列子

    public List<String> getList(List<String> list, Predicate<String> pre) {

        List<String> data = new LinkedList<>();
        for (String s : list) {
            if (pre.test(s)) {
                data.add(s);
            }
        }
        return data;
    }

    @Test
    public void a() {
        List<String> list = Arrays.asList("一", "一二", "一二三");
        List<String> data = getList(list, s -> s.length()==1);
        System.out.println(data);
    }

猜你喜欢

转载自blog.csdn.net/qq_25825923/article/details/81168803