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进行取值

  • 相关阅读:
    第七周进度总结
    第六周进度总结
    第五周进度总结
    《大道至简》读后感
    第四周进度总结
    第三周进度总结
    第二周进度总结
    第一周进度总结
    top工具
    系统监控的一些工具w , vmstat
  • 原文地址:https://www.cnblogs.com/juniorMa/p/14620505.html
Copyright © 2011-2022 走看看