Skip to content

Instantly share code, notes, and snippets.

@upangka
Last active January 10, 2020 05:26
Show Gist options
  • Save upangka/1151b054a083fc14f55a6a40b666bee5 to your computer and use it in GitHub Desktop.
Save upangka/1151b054a083fc14f55a6a40b666bee5 to your computer and use it in GitHub Desktop.
Optional 使用

背景

JOOQ 查询fetch数据有可能为空,所以需要进行判断,但是每次都这么写,感觉太不流畅了。

package org.caucoder.optional;
import javax.swing.text.html.Option;
import java.util.Optional;
public class User {
public User(Integer id) {
this.id = id;
}
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public static void main(String[] args) {
User user = new User(3);
Optional<User> optionalA = Optional.ofNullable(user);
printId(optionalA);
user = null;
Optional<User> optionalB = Optional.ofNullable(user);
printId(optionalB);
}
/**Output
* user存在
* 3
* user不存在
* -1
*
*/
public static void printId(Optional<User> optional){
Integer id = optional.map(item->{
System.out.println("user存在");
return item.getId();
}).orElseGet(()->{
System.out.println("user不存在");
return -1;
});
System.out.println(id);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment