Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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