栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java8 Optional使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java8 Optional使用

详细分析请参考:
1.https://www.cnblogs.com/rjzheng/p/9163246.html
2.https://blog.csdn.net/qq_35387940/article/details/105386359


准备实体类

public class Type {

    private BigDecimal id;
    private String name;
	
    // 省略get和set......
}
public class User {

    private BigDecimal id;
    private String avatar;
    private String email;
    // 实体类组合
    private Type type;

    // 省略get和set......
}
实例1

⏹获取对象中的属性,若不存在返回默认值

User user = null;

// 之前写法,三元表达式
String emailTest1 = ObjectUtils.isEmpty(user) ? "123@qq.com" : user.getEmail();
System.out.println(emailTest1);

// 现在写法,可读性更高
String email1 = Optional.ofNullable(user).map(User::getEmail).orElse("123@qq.com");
System.out.println(email1);
实例2

⏹获取嵌套实体类对象中的属性,若不存在则返回默认值

User user = null;

// 之前写法,需要不断的判断对象和属性是否为null
BigDecimal typeTestId = null;
if (!ObjectUtils.isEmpty(user)) {
    Type type = user.getType();
    if (!ObjectUtils.isEmpty(type)) {
        typeTestId = type.getId();
    } else {
        typeTestId = BigDecimal.ZERO;
    }
} else {
    typeTestId = BigDecimal.ZERO;
}
System.out.println(typeTestId);

// 现在写法,链式调用,只需在最后指定默认值
BigDecimal typeId = Optional.ofNullable(user)
        .map(User::getType)
        .map(Type::getId)
        .orElse(BigDecimal.ZERO);
System.out.println(typeId);
实例3

⏹根据条件获取对象,若满足条件的对象不存在则返回默认对象

User user = null;

// 之前写法
User userTest2 = null;
if (!ObjectUtils.isEmpty(user)) {
    String email = user.getEmail();
    if ("110@qq.com".equals(email)) {
        userTest2 = user;
    }
} else {
    userTest2 = new User();
    userTest2.setEmail("110@qq.com");
}
System.out.println(userTest2);

// 现在写法
User user2 = Optional.ofNullable(user)
        .filter(item -> "110@qq.com".equals(item.getEmail()))
        .orElseGet(() -> {
            User user1 = new User();
            user1.setEmail("110@qq.com");
            return user1;
        });
System.out.println(user2);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/775730.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号