Created
January 27, 2018 12:21
-
-
Save ariesmcrae/d829c5d5704dfcb0699d062d07ed5e05 to your computer and use it in GitHub Desktop.
Java: Return sensible default and avoid NullPointerException in deep hierarchical object tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Optional; | |
public class Main { | |
public static void main (String[] args) { | |
Apple apple = new Apple(); | |
Banana banana = new Banana(); | |
apple.setBanana(banana); | |
Coconut coconut = new Coconut(); | |
banana.setCoconut(coconut); | |
Durian durian = new Durian(); | |
durian.setName("AAA"); | |
coconut.setDurian(durian); | |
String duriaName = Optional.ofNullable(apple) | |
.map(Apple::getBanana) | |
.map(Banana::getCoconut) | |
.map(Coconut::getDurian) | |
.map(Durian::getName) | |
.orElse(null); | |
System.out.println(duriaName); | |
//Output: AAA | |
apple = null; | |
duriaName = Optional.ofNullable(apple) | |
.map(Apple::getBanana) | |
.map(Banana::getCoconut) | |
.map(Coconut::getDurian) | |
.map(Durian::getName) | |
.orElse(null); | |
//Output: null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment