JDK1.8新特性:<二>Lambda表达式

Lambda表达式

<一>基本用法讲述

@FunctionalInterface
public interface IService {
    //无参数无返回值类型
    void serviceLog();

    //只有一个参数无返回值类型
//    void serviceLog(String str);

    //两个参数无返回值类型
//    void serviceLog(String str1,String str2);

    //有返回值类型没有参数
//    String serviceLog();

    //有返回值类型+一个参数
//    String serviceLog(String str);

    //有两个参数+返回值类型
//    String serviceLog(String str1,String str2);
}
import com.jvm.learn.inter.IService;
import org.junit.Test;

public class TestLambda1 {

    /**
     * 测试说明: 测试时根据条件去修改IService接口中的方法
     */

    /**
     * 对Lambda表达式的简单理解:
     *     () 是要参数列表,当没有参数时不可以省略
     *     ()->{} 其实相当于一个类去实现了IService接口,然后通过多态向上转型为父类对象
     *        这样IService就可以调用子类[ ()->{} ]实现的方法了
     */

    //无参数无返回值类型
    @Test
    public void testLambda1(){

        IService service = () -> {
            System.out.println("无参数无返回值类型");
        };
        service.serviceLog();

    }

    //只有一个参数无返回值类型
    @Test
    public void testLambda2(){

//        IService service = (String str)->{
//            System.out.println(str);
//        };
//        service.serviceLog("hello");

        //简化写法 ---> 由于在声明抽象方法时就已经指定参数类型,因此参数类型可以省略;只有一个参数时,()也可省略
//        IService service = str -> {
//            System.out.println(str.toLowerCase());
//        };
//        service.serviceLog("HellO");

    }

    //两个参数无返回值类型
    @Test
    public void testLambda3(){
//        IService service = (str1,str2)->{
//            System.out.println(str1+"今年"+str2+"岁");
//        };
//        service.serviceLog("yby","21");

    }

    //有返回值类型没有参数
    @Test
    public void testLambda4(){
//        IService service = ()->{
//            return "good night";
//        };
//        System.out.println(service.serviceLog());

        //简化写法: 当只有return语句时,{}可以省略,同时return也必须省略
//        IService service=()->"你好";
//        System.out.println(service.serviceLog());

    }

    //有返回值类型+一个参数
    @Test
    public void testLambda5(){
//        IService service = str -> {
//            return str.toLowerCase();
//        };
//        System.out.println(service.serviceLog("HELLO WORLD!"));

        //简化写法
//        IService service = str -> str.toUpperCase();
//        System.out.println(service.serviceLog("hello world"));

    }

    //有两个参数+返回值类型
    @Test
    public void testLambda6(){
//         IService service = (str1,str2)-> str1+":"+str2;
//        System.out.println(service.serviceLog("Object","java"));
    }

}
                                                                                                                                           

<二>进阶

@FunctionalInterface
public interface IService2 {
    double checkOut(double a,double b);
}
import com.jvm.learn.Service2Impl;
import com.jvm.learn.bean.Person;
import com.jvm.learn.inter.IPerson1;
import com.jvm.learn.inter.IPerson2;
import com.jvm.learn.inter.IService2;
import org.junit.Test;

public class TestLambda2 {

    /**
     * Lambda表达式方法引用
     * 方法引用 : 将一个Lambda表达式的实现指向一个已经实现的方法
     * 问题引出: 商店稿促销活动,用户统一打六折,IService2中有
     *    一个checkOut()方法用来结账,如果按照原来的写法每次都要更改打折的数,因此可以将
     *    打折这个数实现为一个方法,让Lambda指向这个方法的实现,这样每次就只需修改打折数,
     *    如果商店不在打折了,那么只需在方法checkOutImpl()中将0.6修改为1,而不用将原来的
     *    业务代码全部改动。
     * 注意事项: 方法引用的方法必须与抽象方法有相同的返回值和参数类型,以及参数顺序一致
     */
    //普通方法引用
    @Test
    public void lambda1(){
        //注意这个类虽然叫Service2Impl 但是便没有实现IService2接口
        Service2Impl service2Impl = new Service2Impl();

        IService2  user1 = (a,b)-> service2Impl.checkOutImpl(a,b);
        System.out.println(user1.checkOut(12.90, 15.06));
        IService2 user2 = (a,b)-> service2Impl.checkOutImpl(a,b);
        System.out.println(user2.checkOut(23, 89));

        //简化写法 语法:  方法隶属者::方法
        //如果是静态方法,那么方法的隶属者就是类,非静态方法就是包含这个方法的类的实例对象
        IService2 user3 = service2Impl::checkOutImpl;
        System.out.println(user3.checkOut(234, 29));
    }

    //构造方法的引用
    @Test
    public void lambda2(){
        IPerson1 ipersonA = ()-> new Person(); //Person的无参构造函数执行......
        //简写
        IPerson1 ipersonB = Person::new;  //Person的无参构造函数执行......

        Person personA = ipersonA.getNoneParamPerson();
        Person personB = ipersonB.getNoneParamPerson();
        //Person{name='null', age=0}  Person{name='null', age=0}
        System.out.println(personA+"  "+personB);

        IPerson2 iPersonC = Person::new;  //Person的有参构造函数执行......
        Person personC = iPersonC.getWithParamPerson("yby",21);
        System.out.println(personC);  //Person{name='yby', age=21}
    }

}

<三>JDK1.8引入的函数式接口

import com.jvm.learn.bean.Person;
import com.jvm.learn.inter.IService3;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class TestLambda3 {
    /**
     * 实战lambda表达式
     */

    /**
     * JDK1.8提供的函数式接口
     *  Predicate<T>
     *  Consumer<T>
     *  Function<T,R>
     *  Supplier<T>
     * 等等.......
     */

    //集合排序
    @Test
    public void sort1(){
        List<Person> persons = Arrays.asList(new Person("张三",17),new Person("李四",12),new Person("小红",14),new Person("王五",21));
        //按年龄对数组排序输出
        //sort()方法的参数是一个函数式接口 Comparator<? super E>
        persons.sort((per1,per2)->per1.getAge()-per2.getAge());

        //[Person{name='李四', age=12},
        // Person{name='小红', age=14},
        // Person{name='张三', age=17},
        // Person{name='王五', age=21}]
        System.out.println(persons);
    }


    /**
     * 闭包问题: 方法的局部变量在方法结束时就会被销毁,但是lambda表达式
     * 可以获取到方法的局部变量
     */
    //闭包演示
    public static Supplier<Integer> getNum(){
        int num = 10;
        return ()-> num; //从这个颜色就可以看出来num不再是局部变量
    }
    public int getNum2(){
        int num = 20;
        return num;
    }
    @Test
    public void testClosure1(){
        System.out.println(getNum().get());
        System.out.println(this.getNum2());
        //思考闭包与直接将局部变量返回有什么区别??
    }

    //闭包的注意事项
    @Test
    public void testClosure2(){
        int a = 21;
        Consumer<Integer> consumer = ele-> System.out.println(a);
        consumer.accept(6); //输出结果21 原因是闭包后,a就是一个常量,不再是局部变量
        //a++; // ----> 会报错 原因,一旦使用了闭包,a就是一个常量,被final修饰
    }


    /**
     * Lambda表达式的延迟执行
     */
    public static void showLog(int level,String msg){
        if (level == 1) System.out.println(msg);
    }
    public static void showLog2(int level, IService3 service3){
        if (level == 1) System.out.println(service3.buildMsg());
    }
    @Test
    public void testLazyExe(){
        String msg1 = "Hello";
        String msg2 = "World";
        showLog(2,msg1+msg2); //只有当level==1时才会执行,但是字符串已经被拼接好了

        //IService3接口定义了一个抽象方法完成相同字符串拼接功能
        showLog2(2,()->msg1+msg2); //只有当判断成立才会进行字符串拼接
    }


    /**
     * Supplier<T> 接口称之为生产型接口,指定接口的泛型是什么,那么接口中就会get()到指定类型的数据
     */
    public static int getMax(Supplier<Integer> supplier){
        return supplier.get();
    }
    @Test
    public void supplier(){
        //求数组的最大元素
        int[] arr = {23,63,34,84,234,456,24,10,8,2,236,109,87};
        int max = getMax(()->{
           int m = arr[0];
            for (int num: arr) {
                if (num > m)   m = num;
            }
            return m;
        });
        System.out.println(max);
    }


    /**
     * Consumer<T> 接口 消费型接口,泛型执行什么类型,就可以使用accept()方法消费什么类型的数据
     */
    public static void consume(String str,Consumer<String> consumer){
        consumer.accept(str);
    }
    @Test
    public void consumer(){
        consume("HELLO WORLD",str -> {
            //将字符串反序输出
            System.out.println(new StringBuffer(str).reverse().toString());
        });
    }
    //Consumer<T>的默认方法 addThen()方法可以将数据交给两个Consumer接口分别消费
    public static void printInfo(String str,Consumer<String> first,Consumer<String> second){
        first.andThen(second).accept(str); //先消费first,再消费second,指定消费的顺序
    }
    @Test
    public void addThen(){
        printInfo("HEllo wOrlD,JaVA",
                first-> System.out.println(first.toLowerCase()),
                second-> System.out.println(second.toUpperCase())
        );
    }


    /**
     * Predicate<T> 接口 逻辑判断接口
     */
    public static boolean predicate(String str, Predicate<String> predicate){
        return predicate.test(str);
    }
    @Test
    public void testPredicate(){
        boolean result = predicate("Hello World",str -> str.equals("HELLO WORLD"));
        System.out.println(result); //false
    }
    //Predicate<T>的默认方法 add() 相当于 && 的作用
    public static boolean add(String str,Predicate<String> pre1,Predicate<String> pre2){
        return pre1.and(pre2).test(str);
    }
    @Test
    public void testAdd(){
        boolean result = add("Hello",
                str->str.length()>3,
                str->str.contains("H")
        );
        System.out.println(result);
        //上述代码的作用其实就是  str.length()>3 && str.contains("H")
    }


    /**
     * Function<T,R> 接口用来根据一个类型的数据得到另外一个类型的数据,前者称为前置条件,后者为后置条件
     */
    public static void change(String s, Function<String,Integer> fun){
        System.out.println(fun.apply(s)); //将String -> Integer
    }
    @Test
    public void apply(){
        change("2343",str->Integer.parseInt(str));
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Avalon712

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值