Optional判断是否为空的处理

        userList.clear();
        userList.add(new User(3, "Tom3"));
        userList.add(new User(2, "Tom2"));
        userList.add(new User(1, "Tom1"));
        Optional<List<User>> optional = Optional.ofNullable(userList);
        optional.ifPresent(new Consumer<List<User>>() {
            @Override
            public void accept(List<User> users) {
                users.stream().forEach(user -> {
                    System.out.println(user.getName());
                });
            }
        });
//        Tom3
//        Tom2
//        Tom1

        Optional<List<User>> optional2 = Optional.ofNullable(userList);
        optional.ifPresent(users -> {
            users.stream().forEach(user -> {
                System.out.println(user.getName());
            });
        });
//        Tom3
//        Tom2
//        Tom1
        
        userList.clear();
        Optional<List<User>> optional3 = Optional.ofNullable(userList);
        optional.ifPresent(users -> {
            users.stream().forEach(user -> {
                System.out.println(user.getName());
            });
        });
        //输出无内容

更多详细请阅读:https://blog.csdn.net/aitangyong/article/details/54564100



猜你喜欢

转载自blog.csdn.net/u010002184/article/details/79715133