Skip to content

Instantly share code, notes, and snippets.

@mmaia
Last active January 16, 2018 13:22
Show Gist options
  • Save mmaia/94431c1f1660cab863af7470eca8800e to your computer and use it in GitHub Desktop.
Save mmaia/94431c1f1660cab863af7470eca8800e to your computer and use it in GitHub Desktop.
Functional java notes

Simple map and flatMap example

reference page

// 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);

Optional example

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment