欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jdk1.8新特性 lambda Optional 备忘记录

程序员文章站 2022-06-04 22:00:49
...

1.lambda实用例子整理

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class LambdaTest {
    public static void main(String[] args) {
        lambda1();//按年龄排序List
        System.out.println("=======================================");
        lambda2();//遍历list 方法1
        System.out.println("=======================================");
        lambda3();//遍历list 方法2
        System.out.println("=======================================");
        lambda4();//筛选年龄大与20的所有人
        System.out.println("=======================================");
        lambda5();//筛选年龄大与20的第一人
    }

    private static void lambda5() {
        List<Person> personList = Arrays.asList(new Person("张三",21,true),new Person("李四",14,true),new Person("王五",21,true));
        Optional<Person> newPerson = personList.stream().filter(item -> item.getAge() > 20).findFirst();
        newPerson.ifPresent(item -> System.out.println(item.getName()));
    }

    private static void lambda4() {
        List<Person> personList = Arrays.asList(new Person("张三",21,true),new Person("李四",14,true),new Person("王五",21,true));
        List<Person> newList = personList.stream().filter(item -> item.getAge() > 20).collect(Collectors.toList());
        newList.forEach(item -> System.out.println(item.getName()));
    }

    private static void lambda3() {
        List<String> list = Arrays.asList("123","456","dongbao");
        list.forEach(LambdaTest::doSomeThing);
    }

    private static void lambda2() {
        List<String> list = Arrays.asList("123","456","dongbao");
        list.forEach(item -> doSomeThing(item));
    }

    private static void doSomeThing(String item) {
        System.out.println(item);
    }

    private static void lambda1() {
        List<Person> personList = Arrays.asList(new Person("张三",21,true),new Person("李四",14,true),new Person("王五",21,true));
        System.out.println("Before Sort=================");
        for (Person person:personList){
            System.out.println(person);
        }
        //年龄按照从小到大
        //personList.sort((Person p1,Person p2)->p1.getAge()-p2.getAge());
        personList.sort((Person p1,Person p2)->{
            if (p2.getAge() == p1.getAge()){
                return p1.getName().compareTo(p2.getName());
            }else{
                return Integer.compare(p1.getAge(),p2.getAge());
            }
        });
        System.out.println("After Sort==================");
        for (Person person:personList){
            System.out.println(person);
        }
    }

    public static class Person implements Serializable {
        private String name;
        private int age;
        private boolean flag;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public boolean isFlag() {
            return flag;
        }

        public void setFlag(boolean flag) {
            this.flag = flag;
        }

        public Person(){}
        public Person(String name, int age, boolean flag) {
            this.name = name;
            this.age = age;
            this.flag = flag;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", flag=" + flag +
                    '}';
        }
    }


}

2.Optional简介

方法 描述
of 把指定的值封装为Optional对象,如果指定的值为null,则抛出NullPointerException
empty 创建一个空的Optional对象
ofNullable 把指定的值封装为Optional对象,如果指定的值为null,则创建一个空的Optional对象
get 如果创建的Optional中有值存在,则返回此值,否则抛出NoSuchElementException
orElse 如果创建的Optional中有值存在,则返回此值,否则返回一个默认值
orElseGet 如果创建的Optional中有值存在,则返回此值,否则返回一个由Supplier接口生成的值
orElseThrow 如果创建的Optional中有值存在,则返回此值,否则抛出一个由指定的Supplier接口生成的异常
filter 如果创建的Optional中的值满足filter中的条件,则返回包含该值的Optional对象,否则返回一个空的Optional对象
map 如果创建的Optional中的值存在,对该值执行提供的Function函数调用
flagMap 如果创建的Optional中的值存在,就对该值执行提供的Function函数调用,返回一个Optional类型的值,否则就返回一个空的Optional对象
isPresent 如果创建的Optional中的值存在,返回true,否则返回false
ifPresent 如果创建的Optional中的值存在,则执行该方法的调用,否则什么也不做
import java.util.Optional;

public class OptinalTest {
    public static void main(String[] args) {
        System.out.println("Optinal of");
        try {
            of();
        }catch (Exception e){

        }
        System.out.println("=========================");
        System.out.println("Optinal ofNullable");
        try {
            ofNullable();
        }catch (Exception e){

        }
        System.out.println("=========================");
        System.out.println("Optinal empty");
        try {
            empty();
        }catch (Exception e){

        }
        System.out.println("=========================");
        System.out.println("Optinal get");
        try {
            get();
        }catch (Exception e){

        }
        System.out.println("=========================");
        System.out.println("Optinal orElse");
        try {
            orElse();
        }catch (Exception e){

        }
        System.out.println("=========================");
        System.out.println("Optinal orElseGet");
        try {
            orElseGet();
        }catch (Exception e){

        }
        System.out.println("=========================");
        System.out.println("Optinal orElseThrow");
        try {
            orElseThrow();
        }catch (Exception e){

        }
        System.out.println("=========================");
        System.out.println("Optinal filter");
        try {
            filter();
        }catch (Exception e){

        }
        System.out.println("=========================");
        System.out.println("Optinal map");
        try {
            map();
        }catch (Exception e){

        }
        System.out.println("=========================");
        System.out.println("Optinal flagmap");
        try {
            flagmap();
        }catch (Exception e){

        }
        System.out.println("=========================");
        System.out.println("Optinal ifpresent");
        try {
            ifpresent();
        }catch (Exception e){

        }

    }

    private static void ifpresent() {
        //ifPresent方法的参数是一个Consumer的实现类,Consumer类包含一个抽象方法,该抽象方法对传入的值进行处理,只处理没有返回值。
        Optional<String> stringOptional = Optional.of("zhangsan");
        stringOptional.ifPresent(e-> System.out.println("我被处理了。。。"+e));
    }

    private static void flagmap() {
        //map方法中的lambda表达式返回值可以是任意类型,在map函数返回之前会包装为Optional。
        //但flatMap方法中的lambda表达式返回值必须是Optionl实例
        Optional<String> stringOptional = Optional.of("zhangsan");
        System.out.println(stringOptional.flatMap(e -> Optional.of("lisi")).orElse("失败"));

        stringOptional = Optional.empty();
        System.out.println(stringOptional.flatMap(e -> Optional.empty()).orElse("失败"));
    }

    private static void map() {
        //如果创建的Optional中的值存在,对该值执行提供的Function函数调用
        //map方法执行传入的lambda表达式参数对Optional实例的值进行修改,修改后的返回值仍然是一个Optional对象
        Optional<String> stringOptional = Optional.of("zhangsan");
        System.out.println(stringOptional.map(e -> e.toUpperCase()).orElse("失败"));

        stringOptional = Optional.empty();
        System.out.println(stringOptional.map(e -> e.toUpperCase()).orElse("失败"));
    }

    private static void filter() {
        //如果创建的Optional中的值满足filter中的条件,则返回包含该值的Optional对象,否则返回一个空的Optional对象
        Optional<String> stringOptional = Optional.of("zhangsan");
        System.out.println(stringOptional.filter(e -> e.length() > 5).orElse("王五"));
        stringOptional = Optional.empty();
        System.out.println(stringOptional.filter(e -> e.length() > 5).orElse("lisi"));
    }

    private static void orElseThrow() {
        //如果创建的Optional中有值存在,则返回此值,否则抛出一个由指定的Supplier接口生成的异常
        Optional<String> stringOptional = Optional.of("张三");
        System.out.println(stringOptional.orElseThrow(CustomException::new));

        Optional<String> emptyOptional = Optional.empty();
        System.out.println(emptyOptional.orElseThrow(CustomException::new));
    }

    private static class CustomException extends RuntimeException {
        private static final long serialVersionUID = -4399699891687593264L;

        public CustomException() {
            super("自定义异常");
        }

        public CustomException(String message) {
            super(message);
        }
    }

    private static void orElseGet() {
        //如果创建的Optional中有值存在,则返回此值,否则返回一个由Supplier接口生成的值
        Optional<String> stringOptional = Optional.of("张三");
        System.out.println(stringOptional.orElseGet(() -> "zhangsan"));

        Optional<String> emptyOptional = Optional.empty();
        System.out.println(emptyOptional.orElseGet(() -> "orElseGet"));
    }

    private static void orElse() {
        //如果创建的Optional中有值存在,则返回此值,否则返回一个默认值
        Optional<String> stringOptional = Optional.of("张三");
        System.out.println(stringOptional.orElse("zhangsan"));

        Optional<String> emptyOptional = Optional.empty();
        System.out.println(emptyOptional.orElse("李四"));
    }

    private static void get() {
        //如果我们创建的Optional对象中有值存在则返回此值,如果没有值存在,则会抛出NoSuchElementException异常。
        Optional<String> stringOptional = Optional.of("张三");
        System.out.println(stringOptional.get());
        Optional<String> emptyOptional = Optional.empty();
        System.out.println(emptyOptional.get());
    }

    private static void empty() {
        //创建一个空的String类型的Optional对象
        Optional<String> emptyOptional = Optional.empty();
    }

    private static void ofNullable() {
        //为指定的值创建Optional对象,不管所传入的值为null不为null,创建的时候都不会报错
        Optional<String> nullOptional1 = Optional.ofNullable(null);
        Optional<String> nullOptional2 = Optional.ofNullable("lisi");
    }

    private static void of() {
        //创建一个值为张三的String类型的Optional
        Optional<String> ofOptional = Optional.of("张三");
        ofOptional.ifPresent(item -> System.out.println(item));
        //如果我们用of方法创建Optional对象时,所传入的值为null,则抛出NullPointerException如下图所示
        Optional<String> nullOptional = Optional.of(null);
    }
}