Created
May 6, 2016 15:23
-
-
Save spencerwi/26ad17413288ef1586ab6e56372140e5 to your computer and use it in GitHub Desktop.
HigherKindedTypes blog post code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface Mappable<A> { | |
public <B> Mappable<B> map(Function<A, B> f); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// assuming that getLastUserWhoLoggedIn might return null | |
String timeZoneOfLastLoggedInUser = Optional.ofNullable(userService.getLastUserWhoLoggedIn()) // Optional<User> | |
.map(user -> user.getAddress()) // Optional<Address> | |
.map(address -> timeZoneService.getTimeZone(address)) // Optional<TimeZone> | |
.map(timeZone -> timeZone.toString()) // Optional<String> | |
.orElse("UTC"); // safely "unwrapping" our Optional<String> to get just a String |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
someListOfListsOfOptionals.stream() | |
.flatMap(listOfOptionals -> listOfOptionals.stream() | |
.map(optional -> optional.map(user -> user.getEmail() ).orElse("")) | |
) //... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public List<Integer> parseNumbers(Function<String, Integer> numberParser, List<String> stringsToParse){ | |
// for every string in stringsToParse, run it through numberParser and add it to a list. | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// assuming that we have a List<Integer> named someListOfIntegers | |
someListOfIntegers.stream() // gives us a Stream<Integer> | |
.map(x -> x.toString()) // now we have a Stream<String> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment