JAVA8之Optional总结

 User user = new User(1000L, "guodong", 99);
        User user1 = new User();
        Optional.ofNullable(user).map(data -> data.getName()).ifPresent(user1::setName);

如上图所示,使用optional可以进行对对象进行赋值。同时也可以使用optional替换三目运算符,代码如下所示:

    public static void main(String[] args) {
//        TestDemo testDemo = new TestDemo();
        TestDemo testDemo = null;
//        testDemo.setCount(null);
        //Java8-Optional:优雅,可读性较好
        int count3 = Optional.ofNullable(testDemo).map(item -> item.getCount()).orElse(1);
        System.out.println(count3);
    }

    private static class TestDemo {

        private Integer count;

        public Integer getCount() {
            return count;
        }

        public void setCount(Integer count) {
            this.count = count;
        }
    }

 

        Optional.ofNullable(item.getProductRef())
                .ifPresent(ref -> {
                    record.setRefProductId(ref.getId());
                    record.setRefProductName(ref.getDisplayText());
                    record.setSalesItemSnapshotId(ref.getSnapshotId());
                });

 

item是入参,record是出参;
Java8的实现细节,参考:https://blog.csdn.net/zjhred/article/details/84976734

 

posted @ 2022-10-12 18:04  郭慕荣  阅读(97)  评论(0编辑  收藏  举报