Lambda表达式使用

为什么使用Lambda表达式

Lambda是一个匿名函数,我们可以把Lambda表达式理解为一段可以传递的代码(将代码像数据一样进行传递)。

lambda的语法结构:

一个括号内用逗号分隔的形式参数,参数是函数式接口里面方法的参数
一个箭头符号:->

方法体,如果是代码块,则需要用“{}”包裹起来

一般方法的引用格式是:
–静态方法: ClassName::methodName。 如 Object ::equals
–成员方法:先new Object(),得到类的obj
–Instance::methodName。 如Object obj=new Object();obj::equals;
–构造函数:ClassName::new

forEach的使用
外部VS forEach内部迭代,以前Java集合无法在内部进行迭代,而现在forEach()可以在内部进行迭代

    public static void main(String[] args) {
        List<String> strs = Arrays.asList("hello","world","javaee");
        System.out.println("-------------------");

        for (String str:strs) {
            System.out.println(str);
        }
        System.out.println("--------------------");
        strs.forEach(System.out::println);
    }

-------------------
hello
world
javaee
--------------------
hello
world
javaee

四大核心函数式接口
Consumer : 消费性接口 void accept(T t);
Supplier : 共给性接口 T get();
Function<T,R> : 函数性接口 T代表参数,R代表返回值 R apply(T t);
Predicate :断言性接口 boolean test(T t);

 
class Test{
    @org.junit.Test
    publilc void test(){
        happy(10000,(money)->System.out.println("happy消费"+money+"元"));
    }
    public void happy(double money,Consumer<double> con){
        con.accept(money);
    }
}

lambda方法引用
方法引用:若lambda体中的内同有方法已经实现了,我们可以使用“方法引用”

(可以理解为方法引用时lambda的另一种表现形式)

主要有三种语法格式:

对象::实例方法名

类::静态方法名

类::实例方法名

class Test{
    //对象::实例方法名
    @org.junit.Test
    public void test(){
        Consumer<String> con = (x) -> System.out.println(x);
        con.accept("haha");
        Consumer<String> con2 = System.out::println;
        con2.accept("haha");
    }
    //类::静态方法名
    @org.junit.Test
    public void test2(){
        Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
        Comparator<Integer> com2 = Integer::compare;
        com.compare(1,2);
        com2.compare(1,2);
    }
    //类::实例方法名
    @org.junit.Test(){
        BiPredicate<String,String> bp = (x,y) -> x.equals(y);
        bp.test("a","a");
        BiPredicate<String,String> bp2 = String::equals;
    }
}

版权声明:本文为youngbird1998原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。