有关Lambda表达式

2019-03-05  本文已影响0人  咖A喱

前言

语法

案例

需求:实现两个数字的增减乘除

package model.four_week;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LambdaDemo {
    public static void main(String[] args) {
//        实现两数相加的lambda表达式
        Mathoperation add = (a, b) -> a + b;
//        实现两数相减的lambda表达式
        Mathoperation differ = (a, b) -> a - b;
//        实现两数相乘的lambda表达式
        Mathoperation multiple = (a, b) -> a * b;
//        实现两数相除的lambda表达式
        Mathoperation division = (a, b) -> a / b;
//        实例化LambdaDemo,使用operate方法
        LambdaDemo lambdaDemo = new LambdaDemo();
//        输出结果
        System.out.println("4+5=" + lambdaDemo.opreate(4, 5, add));
        System.out.println("11-4=" + lambdaDemo.opreate(11, 4, differ));
        System.out.println("2*9=" + lambdaDemo.opreate(2, 9, multiple));
        System.out.println("15/3=" + lambdaDemo.opreate(15, 3, division));
    }

    interface Mathoperation {
        int operation(int a, int b);
    }

    private int opreate(int a, int b, Mathoperation mathoperation) {
        return mathoperation.operation(a, b);
    }
}

输出结果

4+5=9
11-4=7
2*9=18
15/3=5

关于引用

Integer[] integers = new Integer[]{7, 4, 6, 1, 9, 5};
List<Integer> list = new ArrayList<>(Arrays.asList(integers));
list.sort((e1,e2)->el.compareTo(e2));
public class Demo{
    private int a;
    private int b;
    Demo(){}
    Demo(int a,int b){
        this.a=a;
        this.b=b;
    }
    public static boolean compare(int a,int b){
    return a.compareTo(b);
 }
    public boolean compare2(int a,int b){
    return a.compareTo(b);
 }
}
  1. 引用静态方法:将一个静态方法的引用当作参数传入另一个方法中
list.sort((e1,e2)->Demo.compare(e1,e2));

还可以改写为

list.sort(Demo::compare);
  1. 引用对象方法:将一个对象方法的引用当作参数传入另一个方法中

    Demo demo = new Demo();
    
    list.sort((e1,e2)->demo.compare2(e1,e2))
    

    同样可以改写为

    list.sort(demo::compare2);
    
  2. 引用构造器:将一个方法的引用当作参数传入构造器中

list.sort(Demo::new)

变量作用域

上一篇 下一篇

猜你喜欢

热点阅读