Skip to content

Instantly share code, notes, and snippets.

@calaveraInfo
Last active February 21, 2017 12:18
Show Gist options
  • Save calaveraInfo/821c0ae691e48eeaeeafe5381977cc34 to your computer and use it in GitHub Desktop.
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
@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