Skip to content

Instantly share code, notes, and snippets.

@csturtevant
Last active July 17, 2016 18:05
Show Gist options
  • Save csturtevant/6c9a69dfcf80809ba6af289430279703 to your computer and use it in GitHub Desktop.
Save csturtevant/6c9a69dfcf80809ba6af289430279703 to your computer and use it in GitHub Desktop.
Interesting Use Of Optional
String stringWithNull = null;
String nullResult = Optional.ofNullable(stringWithNull)
.map(Integer::valueOf)
.map(i -> i + 1)
.map(Object::toString)
.orElse("number not present"); //This or else from optional is of most interest
System.out.println(nullResult);
String numberInString = "100";
String result = Optional.ofNullable(numberInString)
.map(Integer::valueOf)
.map(i -> i + 1)
.map(Object::toString)
.orElse("number not present"); //This or else from optional is of most interest
System.out.println(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment