// define a function that maps String to Long
Function<String, Long> toLong = Long::parseLong;
//aplying the function to the possible string
Optional<String> someString = Optional.of("12L");
Optional<Long> someLong = someString.map(toLong);
//applying the function to all strings
Stream<String> someStrings = Stream.of("10L", "11L");
Stream<Long> someLongs = someStrings.map(toLong);
Now with an Optional being returned by our function, so we need flatMap:
Function<String, Optional<Long>> toLongOpt = Long::parseLongOpt;
Optional<String> someString = Optional.of("12L");
Optional<Long> someLong = someString.flatMap(toLongOpt);
When using an Optional in a declarative way, we are able to execute a map function on it. The lambda supplied with the map will only be executed if the Optional is filled with a value, otherwise it will do nothing.
public void execute() {
Optional<String> maybeString = Optional.of("foo");
maybeString.map(this::runIfExist);
}
private String runIfExist(String str) {
System.out.println("only run if optional is filled ");
return str;
}
Some flows with optional:
public void execute() {
Optional<String> maybeString = Optional.of("foo");
String newString = maybeString
.map(this::runIfExist)
.orElse(runIfEmpty());
System.out.println(newString);
}
private String runIfExist(String str) {
System.out.println("only run if optional is filled ");
return str;
}
private String runIfEmpty() {
System.out.println("only run if empty");
return "empty";
}
The above code fragment results in:
only run if optional is filled
only run if empty
foo