Lambda表达式

基本语法:

<函数式接口><变量名> = <参数1,参数2...> -> {
    //方法体
};

引入了新的操作符:->(箭头操作符),->将表达式分为两个部分
左侧:(参数1,参数2...)表示参数列表
右侧:{}内部是方法体
注意事项:
  • 1、新参列表的数据类型会自动推断
  • 2、如果形参列表为空,只需保留()
  • 3、如果形参是有1个,()可以省略,只需要参数名称即可
  • 4、如果执行语句只有一句,且无返回值,{}可以省略若有返回值,
  • 则若想省去{},则必须同时省去return,且执行语句也保证只有一句
  • 5、Lambda不会生成一个单独的内部类文件

例:

//无参
public class Demo {
    public static void main(String[] args) {
        //匿名内部类
        Runnable run = new Runnable() {
            @Override
            public void run() {
                System.out.println("我是一个小线程!");
            }
        };
     //Lambda表达式
        Runnable run1=()->System.out.println("我是两个小线程!");
     new Thread(run1).start();
    //new Thread(()->System.out.println("我是三个小线程!")).start();
}

//有参
//匿名内部类
Comparator<String> comparator = new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return o1.length()-o2.length();
    }
};
//Lambda表达式
Comparator<String> com1 = (String o1,String o2)->{return o1.length()-o2.length();};
Comparator<String> com2=(o1,o2)->o1.length()-o2.length();

TreeSet<String> set  = new TreeSet<>(comparator);

自定义接口

//interface
@FunctionalInterface --判断是否为函数式接口(只能标记在有且仅有一个抽象方法"的接口上)
public interface Usb {
    void service();
}

//---------------class
      Usb usb = new Usb() {
            @Override
            public void service() {
                System.out.println("我是鼠标!");
            }
        };
        Usb us = ()-> System.out.println("我是");
        ru(usb);
        ru(us);
        ru(()-> System.out.println("我是键盘!"));
        }

    public static void ru(Usb usb){
        usb.service();
    }

一、函数式接口  

  如果一个接口只有一个抽象方法,则该接口称为函数式接口,

函数式接口可以使用Lanbda表达式,Lambda表达式会被匹配到这个抽象方法上。

1.常见的函数式接口
Consumer<T>消费型接口 参数类型T 返回类型void
说明:void accept(T t);对类型为T的对象应用操作

//Consumer消费型接口
public static void happy(Consumer<Double> consumer,double money){
        consumer.accept(money);
}

//匿名内部类
        Consumer<Double> con = new Consumer<Double>() {
            @Override
            public void accept(Double aDouble) {
                System.out.println("今天到聚餐!");
            }
        };
//Lambda
        Consumer<Double> con1 = (a)-> System.out.println("今天到网吧!");
        happy(con,100);
        happy(con1,200);
        happy((a)-> System.out.println("今天到酒吧!"),200);

Supplier<T>供给型接口 参数类型无 返回类型T

说明:T get(); 返回类型为T的对象

//Supplier供给型接口
public static int[] getNum(Supplier<Integer> supplier,int count){
       int[] arr = new int[count];
        for (int i = 0; i < count; i++) {
            arr[i] = supplier.get();
        }
        return arr;
}

//匿名内部类
        Supplier<Integer> supplier = new Supplier<Integer>() {
            @Override
            public Integer get() {
                return new Random().nextInt(100);
            }
        };

        int[] a= getNum(supplier,3);
//Lambda表达式
        Supplier<Integer> sup = ()-> new Random().nextInt(1000);
        int[] b = getNum(sup,1000);

        int[] c = getNum(()->new Random().nextInt(10),2);
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.toString(b));
        System.out.println(Arrays.toString(c));

Function(T,R)函数型接口 参数类型T 返回类型boolean
说明:R apply(T t);对类型为T的对象应用操作,并返回类型为R类型的对象

 //function函数型接口
public static String handlerString(Function<String,String> function,String str){
        return function.apply(str);
}

//匿名内部类
        Function<String,String> fun = new Function<String, String>() {
            @Override
            public String apply(String s) {
                return s.toUpperCase();
            }
        };

        System.out.println(handlerString(fun,"hello"));
//Lambda表达式
        System.out.println(handlerString((s)-> s.trim(),"    nihao     "));

        List<String> list1  = new ArrayList<>();
        list1.add("zhangsan");
        list1.add("lisi");
        list1.add("wangwu");
        list1.add("zhaoliu");

Predicate(T)断言型接口 参数类型T 返回类型boolean
说明:boolean test(T t);确认类型为T的对象是否满足条件,并返回boolean;类型。

//Predicate断言类型
public static List<String> filterNames(Predicate<String> predicate, List<String> list){
        List<String> returnList = new ArrayList<>();
        for (String str:list) {
            if(predicate.test(str)){
                returnList.add(str);
            }
        }
        return  returnList;
}

//匿名内部类
        Predicate<String> predicate = new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.startsWith("zh");
            }
        };

        List<String> test =  filterNames(predicate,list1);
        System.out.println(test);
//Lambda表达式
        System.out.println("-->"+filterNames((t)->t.startsWith("zh"),list1));

 二、方法引用

  方法引用是Lambda表达式的一种简写形式。如果Lambda表达式方法体中
只是调用一个特定的已经存在的方法,则可以使用方法引用。

常见形式
对象::实例方法
类::静态方法
类::实例方法
类::new
public class Demo2 {
    public static void main(String[] args) {
        //1、对象::实例方法
        Consumer<String> c = s-> System.out.println(s);
        c.accept("hello");
        Consumer<String> c1 = System.out::println;
        c1.accept("hello");

        //2、类::静态方法
        Comparator<Integer> com = (o1,o2)->Integer.compare(o1,o2);
        Comparator<Integer> com1 = Integer::compare;

        //3、类::实例方法
        Function<Employee,String> fun =(e)->e.getName();
        Function<Employee,String> fun1 =Employee::getName;

        //4、类::new
        Supplier<Employee> supplier = ()->new Employee();
        Supplier<Employee> supplier1 = Employee::new;
    }
原文地址:https://www.cnblogs.com/64Byte/p/14508009.html