JAVA8自定义Lambda表达式的常见使用方法

根据使用场景不同,Lambda表达式的常见使用方法通常有三种写法。



import org.junit.Test;

/**
 * Lambda Test
 * Created by Joker on 2017/8/8.
 */
public class LambdaD {

    static class Math {
        private static Object execute(Integer... args) {
            Integer sum = 0;
            for (Integer arg : args) {
                sum += arg;
            }
            return sum;
        }
    }

    interface Executor {
        Object execute(Integer... args);
    }

    private Object runExecute(Executor executor, Integer... args) {
        return executor.execute(args);
    }

    @Test
    public void test() {
        System.out.println(runExecute(Math::execute, 1, 2, 3));
        System.out.println(runExecute(args -> Math.execute(args), 1, 2, 3));
        System.out.println(runExecute((Integer... args)-> {return args[0]+args[1]+args[2];}, 1, 2, 3));
    }


}

以下简单的仿照List forEach方法:



import com.springtest.colligate.Add;
import org.junit.Test;

import java.util.*;
import java.util.function.Consumer;

/**
 * Lambda Test
 * Created by Joker on 2017/8/8.
 */
public class LambdaE {

    class CustomerList<T>{
        List<T> listData = new ArrayList<>();

        void add(T t) {
            listData.add(t);
        }

        void forEach(Executor<? super T> action) {
            Objects.requireNonNull(action);
            for (T t : listData) {
                action.runAction(t);
            }
        }
    }

    interface Executor<T> {
        void runAction(T t);
    }


    @Test
    public void test(){
        CustomerList<String> aaa = new CustomerList<String>();
        aaa.add("WuYiFan");
        aaa.add("TFBoys");
        aaa.add("Angelababy");
        aaa.forEach(a->{System.out.println(a);});
    }


}

总结:当某个类在需要接口类型构造方法时,我们可以以Lambda的形式申明该接口的实例。其本质是对传入的对象做怎样的操作。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值