lambda表达式运用

目录

1             Lambda简介... 2

1.1      什么是lambda\ 2

1.2      Lambda对接口的要求... 2

1.3      函数式接口... 2

1.4      代码... 2

2             Lambda语法... 6

2.1      代码... 6

3             Lambda语法精简... 12

3.1      参数精简:由于参数类型在抽象方法中已经定义,参数类型可以自动推断,可以省略。    12

3.2      一个参数可以省略小括号()... 12

3.3      如果方法体只有一条语句可以省略大括号... 12

3.4      如果方法体中只有唯一一条返回语句,此时可以省略return,必须省略大括号... 12

4             方法进阶... 13

4.1      调用方法... 13

4.2      调用对象构造方法... 16

5             集合排序... 19

5.1      TreeSet集合排序... 20

5.2      Foreach的使用... 22

5.3      条件判断进行过滤删除... 24

6             系统内置函数式接口... 27

6.1      闭包问题... 28

 

 

 

 

1      Lambda简介

1.1    什么是lambda\

一句话就是匿名函数

1.2    Lambda对接口的要求

并不是所有的接口都可以使用lambda表达式来实现,要求接口中必须要定义一个抽象方法,有且只能有一个

 

1.3    函数式接口

使用@FunctionInterface 注解修饰

接口中有且只能有一个抽象方法的接口就是函数式接口

 

1.4    代码

package lambdaCase;



/**定义一个函数式接口*/
/** @FunctionalInterface 修饰  */

@FunctionalInterface
interface Comparator{
    /**有且只能有一个抽象方法 */
    int compare(int a , int b);
}

/**接口实现类 实现求两个数的和 */
class MyComparator implements  Comparator{
    @Override
    public int compare(int a, int b) {
        return a + b ;
    }
}


public class LambdaCase1 {

    public static void main(String[] args) {

        /** 1. 使用接口实现类实现求两个数大小的和 */
        MyComparator myComparator = new MyComparator();
        int compare = myComparator.compare(1, 3);
        System.out.println(compare); //4

        /** 2.使用匿名内部类实现 */
        Comparator comparator = new Comparator() {
            @Override
            public int compare(int a, int b) {
                return a + b;
            }
        };
        int compare1 = comparator.compare(2, 3);
        System.out.println(compare1);//5

        /** 3.使用Lambda表达式来实现接口*/
        /** 返回值类型 必须是接口类型 还是需要返回对象后
         * 使用对象才能调用方法 实质就是简化了 实现的形式  */
        Comparator compare3 = (a, b) -> a + b;
        int res = compare3.compare(5, 6);

        System.out.println(res);//11
    }


}

 

 

2      Lambda语法

2.1    代码

package lambdaCase;

/**
 * 接口列表
 */

/**无参数无返回值*/
@FunctionalInterface
interface interface1 {
   void show();
}

/**一个参数无返回值*/
@FunctionalInterface
interface interface2 {
    void show(String str);
}

/**多个参数无返回值*/
@FunctionalInterface
interface interface3 {
    void show(String str1,String str2);
}

/**无参数有回值*/
@FunctionalInterface
interface interface4 {
    String show();
}

/**一个参数有回值*/
@FunctionalInterface
interface interface5 {
    int show(int a);
}

/**多个参数有回值*/
@FunctionalInterface
interface interface6 {
    int show(int a , int b );
}

/**可变参数 */
@FunctionalInterface
interface interface7 {
    int show(int ...a);
}


public class LambdaCase2 {
    /***
     * Lambda 表达式的基础语法:
     * Lambda 是一个匿名函数
     * 函数 关注 参数列表 方法体
     *
     * () :用来表示参数列表
     * {} :用来描述方法体
     * -> : Lambda运算符 , 读作 goes to
     *
     */

    public static void main(String[] args) {
        /**使用Lambda表达式实现以上6个接口*/

      interface1 show1 =  () -> { System.out.println("show1...."); };
      show1.show();//show1....

        interface2 show2 = (String str) -> {
            System.out.println(str.toUpperCase());
        };
        show2.show("hello lambda");//HELLO LAMBDA


        interface3 show3 = (String str1,String str2) ->{
            System.out.println(str1.toUpperCase()+"\001"+str2);
        };
        show3.show("say","Hello");//SAYHello


        interface4 show4 = () -> {
            return "this is a test Lambda";
        };
        System.out.println(show4.show());//this is a test Lambda

        interface5 show5 = (a) -> { return a * a ; } ;
        System.out.println(show5.show(9));//81

        interface6 show6 = (a , b ) ->{ return  a + b * a * b; };

        System.out.println(show6.show(2, 3));//20


        interface7 show7 = (int ...a) ->{
            int sum = 0;
            for (int i = 1; i <a.length + 1 ; i++) {
                sum += i;
            }
            return sum;
        } ;

        System.out.println(show7.show(1, 2, 3, 4, 5));//15
       

    }
   

}

 

 

 

3      Lambda语法精简

3.1    参数精简:由于参数类型在抽象方法中已经定义,参数类型可以自动推断,可以省略。

3.2    一个参数可以省略小括号()

3.3    如果方法体只有一条语句可以省略大括号

3.4    如果方法体中只有唯一一条返回语句,此时可以省略return,必须省略大括号

 

4      方法进阶

4.1    调用方法

package lambdaCase;


/**lambda表达式调用方法 */

interface E{
    int show(int a );
}

interface F{
   int show(int a , int b);
}

public class Functions {

    public static int sum(int a , int b){
        return a + b ;
    }

    public int multiplication(int a , int b){
        return a * b ;
    }

    public static int mu(int a){
        return a * a ;
    }


    public static void main(String[] args) {
        /***
         * 方法引用:
         * 可以快速的将一个lambda表达式的实现指向一个已经实现的方法。
         * 语法:1. 方法的隶属者(类、对象)::方法名
         *      2.(参数列表) -> 方法(参数列表)
         */
        /**
         * 注意:
         * 1.参数数量和类型要和接口中定义的方法一致
         * 2.返回值的类型一定要和接口中定义的方法一致
         */

        E e = a -> mu(a);
        System.out.println(e.show(12));//144
        E e1 = Functions::mu;
        System.out.println(e1.show(11));//121

        F f = Functions::sum;
        System.out.println(f.show(3, 5));//8

        F f1 = new Functions()::multiplication;
        System.out.println(f1.show(211, 1));//211

        F f2 = (a, b) -> sum(a,b);
        System.out.println(f2.show(5, 6));//11


    }

}

 

 

4.2    调用对象构造方法

package lambdaCase;



/** lambda 表达式调用构造方法*/

@FunctionalInterface
interface P1{
  Person  getPerson();
}

@FunctionalInterface
interface P2{
    Person  getPerson(int id , String name);
}

public class Person {
    private int id;
    private String name;

    public Person() {
        System.out.println("调用无参构造器...");
    }

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
        System.out.println("...调用有参构造器....");
    }

    public static void main(String[] args) {
        /**测试 lambda 表达式调用构造方法 */
        P1 p1 = Person::new;
        Person person = p1.getPerson();//调用无参构造器...

        P2 p2 = Person::new;
        Person ha = p2.getPerson(9527, "华安");//...调用有参构造器....



    }
}

 

 

5      集合排序

package lambdaCase;

import java.util.ArrayList;

/**集合排序*/
public class ListCase {

    public static void main(String[] args) {
        ArrayList<Person> list = new ArrayList<Person>();

        list.add(new Person(1,"lilei"));
        list.add(new Person(5,"hanmeimei"));
        list.add(new Person(2,"lily"));
        list.add(new Person(3,"polly"));
        list.add(new Person(4,"uncle wang"));

        Integer i  = 10;
        i.compareTo(i);

        int ii = 11;



        //按照ID排序
        list.sort((x,y)-> Integer.compare(x.id , y.id ));

        System.out.println(list);
//[Person{id=1, name='lilei'}, Person{id=2, name='lily'}, Person{id=3, name='polly'},
//        Person{id=4, name='uncle wang'}, Person{id=5, name='hanmeimei'}]
    }



}

 

 

 

5.1    TreeSet集合排序

 

package lambdaCase;

import java.util.TreeSet;

public class TreeSetCase {
    public static void main(String[] args) {

        // TreeSet 自带顺序 放入的元素必须是实现Comparator接口
        //返回 0 就会把ID相同的去除掉
        TreeSet<Person> set = new TreeSet<Person>(
                (x , y ) -> {
                    if(x.id >= y.id){
                        return -1 ;
                    }else {
                        return 1;
                    }
                }
        );

        set.add(new Person(1,"lilei"));
        set.add(new Person(5,"hanmeimei"));
        set.add(new Person(2,"lily"));
        set.add(new Person(3,"polly"));
        set.add(new Person(4,"uncle wang"));

        System.out.println(set);
        //[Person{id=5, name='hanmeimei'}, Person{id=4, name='uncle wang'}, Person{id=3,
        // name='polly'}, Person{id=2, name='lily'}, Person{id=1, name='lilei'}]

    }
}

 

 

 

5.2    Foreach的使用

package lambdaCase;

import java.util.ArrayList;
import java.util.Collections;

public class ForeachCase {

    public static void main(String[] args) {
        ArrayList<Integer> list =  new ArrayList<Integer>();

        Collections.addAll(list,1,2,3,4,5,6,7,8,9,10);

        //将集合中的每一个元素都带人到accept中
        //遍历集合
        list.forEach(System.out::println);

        //输入集合中所有的偶数
        list.forEach(e -> {
            if(e % 2 == 0 ){
                System.out.println(e);
            }
        });

    }




}

 

 

 

5.3    条件判断进行过滤删除

 

package lambdaCase;

import java.util.ArrayList;

public class RemoveIfCase {
    public static void main(String[] args) {
        /**删除集合中满足条件的数据*/

        ArrayList<Person> list = new ArrayList<Person>();

        list.add(new Person(1,"lilei"));
        list.add(new Person(5,"hanmeimei"));
        list.add(new Person(2,"lily"));
        list.add(new Person(3,"polly"));
        list.add(new Person(4,"uncle wang"));

        /**删除ID 大于 3 的用户 */
        //将集合中每一个元素都带入到test方法中,如果返回值是true 则删除这个元素
        /***
         *
         * @FunctionalInterface
         * public interface Predicate<T> {
         *
         *boolean test (T t);
         *
         */
        list.removeIf(e -> e.id > 3 );

        System.out.println(list);
        //[Person{id=1, name='lilei'}, Person{id=2, name='lily'}, Person{id=3, name='polly'}]

    }
}

 

 

 

 

 

6      系统内置函数式接口

import java.util.function.*;

 

 

 

 

 

6.1    闭包问题

 

 

posted @ 2019-12-15 12:08  马鞍山  阅读(166)  评论(0)    收藏  举报