Lambda 表达式语法学习

 

 一、初识lambda表达式,lambda表达式作为函数入参。

public static void main(String[] args) {
        //1、使用lambda表达式申明为MylambdaInterface接口的实现
        MylambdaInterface aBlockOfCode = (s) -> System.out.println(s);
        aBlockOfCode.doSomeShit("Hello"); //Hello


        enact(aBlockOfCode, "Hello"); //Hello
        //2、Lambda作为参数传递给函数
        enact((s) -> System.out.println(s), "Hello");//Hello

        //3、多行时,大括号不能省略
        enact((s) -> {
            System.out.print("Hello ");
            System.out.println(s);
        }, "World");//Hello World
    }

    public static void enact(MylambdaInterface myLambda, String s) {
        myLambda.doSomeShit(s);
    }

    @FunctionalInterface
    public interface MylambdaInterface {//申明函数式编程接口
        void doSomeShit(String s);
    }

二、 demo

public class Learn2 {
    public static void main(String[] args) {
        List<Person> guiltyPersons = Arrays.asList(new Person("Yixing", "Zhao", 25),
                new Person("Yanggui", "Li", 30),
                new Person("Chao", "Ma", 29));
        //Lambda表达式作为参数,传递给函数
        checkAndExecute(guiltyPersons, p -> p.getLastName().startsWith("Z"), p -> System.out.println(p.getFirstName()));
    }

    public static void checkAndExecute(List<Person> personList, NameChecker nameChecker, Executor executor) {
        for (Person p : personList) {
            if (nameChecker.check(p)) {
                executor.execute(p);
            }
        }
    }

    @FunctionalInterface
    interface NameChecker {
        boolean check(Person p);
    }

    @FunctionalInterface
    interface Executor {
        void execute(Person p);
    }
}


@Data
@AllArgsConstructor
public class Person {
    private String firstName;
    private String lastName;
    private int age;
}

三、使用stream()代替for循环,Java 8函数式接口包里的Predicate和Consumer 

public class Learn3 {
    public static void main(String[] args) {
        List<Person> guiltyPersons = Arrays.asList(new Person("Yixing", "Zhao", 25),
                new Person("Yanggui", "Li", 30),
                new Person("Chao", "Ma", 29));
        //1、Lambda表达式作为参数,传递给函数。简化:用Iterable.forEach()取代foreach loop
        checkAndExecute(guiltyPersons, p -> p.getLastName().startsWith("Z"), p -> System.out.println(p.getFirstName()));
        //2、利用stream()替代静态函数
        guiltyPersons.stream().filter(person -> person.getLastName().startsWith("Z")).forEach(p->System.out.println(p.getFirstName()));
        //3、利用Method reference来继续简化。所谓Method reference, 就是用已经写好的别的Object/Class的method来代替Lambda expression。
        guiltyPersons.stream().filter(person -> person.getLastName().startsWith("Z")).forEach(System.out::println);

        guiltyPersons.stream().filter(person -> person.getLastName().startsWith("Z")).forEach(
                p->{
                    System.out.print("Hello "+ JSON.toJSONString(p.getFirstName()));
                    System.out.println(JSON.toJSONString(p.getLastName()));
                }
        );
    }

    public static void checkAndExecute(List<Person> personList, Predicate<Person> predicate, Consumer<Person> consumer) {
        /*for (Person p : personList) {
            if (predicate.test(p)) {
                consumer.accept(p);
            }
        }*/
        personList.forEach(person -> {
            if (predicate.test(person)) {
                consumer.accept(person);
            }
        });
    }

    /*@FunctionalInterface
    interface Predicate<T> {
        boolean test(T t);
    }

    @FunctionalInterface
    interface Consumer<T> {
        void accept(T t);
    }*/
}

四、Optional如果结合Lambda,简化ifnull的判断

public class Learn4 {
    public static void main(String[] args) {
        Person person2 = new Person("Chao", "Ma", 29);
        Person person = null;
        Optional<Person> personOpt = Optional.ofNullable(person);
        //1、ifPresent存在则执行
        personOpt.ifPresent(System.out::println);
        if (person != null) {
            System.out.println(JSON.toJSONString(person));
        }
        //2、存在则返回,不存在则返回person2
        System.out.println(personOpt.orElse(person2));
        //3、存在则返回,不存在执行Lambda表达式
        System.out.println(personOpt.orElseGet(() -> new Person("Chao", "Ma", 29)));
        //4、如果LastName不为空,返回大小,否则返回空。
        System.out.println(personOpt.map(p -> p.getLastName()).map(name -> name.toUpperCase()).orElse(null));

        System.out.println(Optional.ofNullable(person).map(p -> p.getLastName()).map(name -> name.toUpperCase()).orElse(null));
    }
}

参考https://mp.weixin.qq.com/s/TjetWEvJsSbJ9N-51ECkbw文章学习Lambda语法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值