zoukankan      html  css  js  c++  java
  • Optional编程实例

     @Test
        public void optionalTest() throws NoSuchMethodException {
            String firstValue = null;
            Optional<String> key = Optional.ofNullable(firstValue);
            String defaultValue = key.orElse("apple");
            if (!key.isPresent()) {
                System.out.println(defaultValue + "001");
            }
            System.out.println(defaultValue);
        }

    结果是 

    apple001
    apple

    学习新的写法,新的api

    =======================2021-11-12 20:29 =========================

    public static class Apple {
            int size;
            int price;
            Color color;
            public Apple(int size , int price, Color color) {
                this.size = size;
                this.price = price;
                this.color = color;
            }
    
            public void setSize(int size) {
                this.size = size;
            }
    
            public Color getColor() {
                return this.color;
            }
        }
    public static class Color {
    
            public Color(int color, Cat cat) {
                this.color = color;
                this.cat = cat;
            }
            int color;
            Cat cat;
    
            public Cat getCat() {
                return this.cat;
            }
        }
    public static class Cat {
            int age;
        }

      三个class层层嵌套

    Apple e = new Apple(1, 1, new Color(1,null));
            //Apple e = new Apple(1, 1, null);
            Cat color = Optional.ofNullable(e).map(u -> u.getColor()).map(c -> c.getCat()).orElse(new Cat());

    map方法返回值还是Optional,调用orElse进行取值

  • 相关阅读:
    html的一些基本属性介绍
    html的一些基本语法学习与实战
    getline()和get()的使用区别
    浅谈JS执行环境及作用域
    vue的第一个commit分析
    移动端适配-rem(新)
    电商类业务梳理
    不同类型的状态码及含义
    TCP/IP简记
    前端性能优化小结(持续更新)
  • 原文地址:https://www.cnblogs.com/juniorMa/p/14620505.html
Copyright © 2011-2022 走看看