AdSense

網頁

2019/1/15

Java Optional.ofNullable check null, if not null call the method, if is null return orElse

Memo how to use Optional.ofNullable() to check if an object is null or not. If the object is null, then return the default value by using orElse(); If it is not null, then call the object's method.

The key is using map().

Example

User user1 = null;
String name1 = Optional.ofNullable(user1).map(User::getName).orElse(null);
System.out.println(name1); // null

User user2 = new User();
String name2 = Optional.ofNullable(user2).map(User::getName).orElse("No result");
System.out.println(name2); // No result

User user3 = new User();
user3.setName("John");
String name3 = Optional.ofNullable(user3).map(User::getName).orElse(null);
System.out.println(name3); // John

Memo this because I used wrong as below:

User user1 = null;
String name1 = Optional.ofNullable(user1).orElse(null).getName(); // lead to NullPointerException
System.out.println(name1);


沒有留言:

AdSense