June 2018
Intermediate to advanced
280 pages
7h 46m
English
A monad applies a function that returns a wrapped value to a wrapped value. Java contains examples such as Stream, CompletableFuture, and the already-presented Optional. The flatMap function does this by applying the given function, as the following code demonstrates, to a list of ZIP codes that may or may not exist in a ZIP code map:
jshell> Map<Integer, String> codesMapping = Map.of(400500, "Cluj-Napoca", 75001, "Paris", 10115, "Berlin", 10000, "New York")codesMapping ==> {400500=Cluj-Napoca, 10115=Berlin, 10000=New York, 75001=Paris}jshell> List<Integer> codes = List.of(400501, 75001, 10115, 10000)codes ==> [400501, 75001, 10115, 10000]jshell> codes.stream().flatMap(x -> Stream.ofNullable(codesMapping.get(x)))$3 ==> java.util.stream.ReferencePipeline$7@343f4d3d ...Read now
Unlock full access