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

  • 相关阅读:
    二分图最大匹配(匈牙利算法) POJ 3041 Asteroids
    贪心 FZU 2013 A short problem
    数学 FZU 2074 Number of methods
    莫队算法/二分查找 FZU 2072 Count
    畅通工程 HDU
    Minimum Inversion Number~hdu 1394
    I Hate It HDU
    A Simple Problem with Integers~POJ
    敌兵布阵
    Coins HDU
  • 原文地址:https://www.cnblogs.com/juniorMa/p/14620505.html
Copyright © 2011-2022 走看看