Last active
February 21, 2017 12:18
-
-
Save calaveraInfo/821c0ae691e48eeaeeafe5381977cc34 to your computer and use it in GitHub Desktop.
Java 8 Optional: using map + null return value is allowed, no need to do flatMap + ofNullable. http://calavera.info/v3/blog/2016/11/17/nic.html
This file contains 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
@Test | |
public void testOptional() { | |
assertEquals(Optional.of( | |
new AClass()) | |
.map(AClass::getSomeObject) | |
.map(BClass::getSomeText) | |
.map(String::trim) | |
.orElse(""), ""); | |
assertEquals(Optional.of( | |
new AClass(new BClass())) | |
.map(AClass::getSomeObject) | |
.map(BClass::getSomeText) | |
.map(String::trim) | |
.orElse(""), ""); | |
assertEquals(Optional.of( | |
new AClass(new BClass(" test "))) | |
.map(AClass::getSomeObject) | |
.map(BClass::getSomeText) | |
.map(String::trim) | |
.orElse(""), "test"); | |
assertEquals(Optional.of( | |
new AClass()) | |
.flatMap(aClass -> Optional.ofNullable(aClass.getSomeObject())) | |
.flatMap(bClass -> Optional.ofNullable(bClass.getSomeText())) | |
.map(String::trim) | |
.orElse(""), ""); | |
assertEquals(Optional.of( | |
new AClass(new BClass())) | |
.flatMap(aClass -> Optional.ofNullable(aClass.getSomeObject())) | |
.flatMap(bClass -> Optional.ofNullable(bClass.getSomeText())) | |
.map(String::trim) | |
.orElse(""), ""); | |
assertEquals(Optional.of( | |
new AClass(new BClass(" test "))) | |
.flatMap(aClass -> Optional.ofNullable(aClass.getSomeObject())) | |
.flatMap(bClass -> Optional.ofNullable(bClass.getSomeText())) | |
.map(String::trim) | |
.orElse(""), "test"); | |
} | |
public class AClass { | |
private BClass someObject; | |
public AClass() {} | |
public AClass(BClass someObject) { | |
this.someObject = someObject; | |
} | |
public BClass getSomeObject() { | |
return someObject; | |
} | |
} | |
public class BClass { | |
private String someText; | |
public BClass() {} | |
public BClass(String someText) { | |
this.someText = someText; | |
} | |
public String getSomeText() { | |
return someText; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment