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 @   郭慕荣  阅读(105)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2021-10-12 JUC-Exchanger总结
点击右上角即可分享
微信分享提示