1、三目表达式
获取对象的属性,判断对象是否为空,为空返回默认值
C c = new C("c");
String name = c != null ? c.getName() :DEFAULT_NAME;
2、判断不为空再赋值
User user = userDao.getUser(id);
if (user!= null) {
user.setName("张三");
}
// 使用Optional
Optional.ofNullable(user).ifPresent(p -> user.setName("李四"));
3、型之间的转换,当没有值的时候返回一个默认值
int timeout = Optional.ofNullable(RedisProperties.getTimeout())
.map(x -> Long.valueOf(x.toMillis()).intValue())
.orElse(10000);
4、判断不为空 set
before
BaseMasterSlaveServersConfig smssc = new BaseMasterSlaveServersConfig();
if (clientName != null) {
smssc.setClientName(clientName);
}
if (idleConnectionTimeout != null) {
smssc.setIdleConnectionTimeout(idleConnectionTimeout);
————————————————
after
ptional.ofNullable(clientName).ifPresent(smssc::setClientName);
Optional.ofNullable(idleConnectionTimeout).ifPresent(smssc::setIdleConnectionTimeout);
5、集合判断 为空返回空集合
List<String> list = null;
List<String> newList = Optional.ofNullable(list).orElse(new ArrayList());
newList.forEach(x -> System.out.println(x));
、
标签:ofNullable,ifPresent,Optional,else,user,null,smssc,消除
From: https://www.cnblogs.com/cherychina/p/17493686.html