Created
September 19, 2019 18:24
-
-
Save haroldl/aee6a407a01131345fc4ecb1b9c9bec2 to your computer and use it in GitHub Desktop.
This file contains 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
import java.util.Arrays; | |
import java.util.List; | |
import static java.lang.String.join; | |
import static java.util.Collections.emptyList; | |
import static java.util.Collections.nCopies; | |
import static java.util.stream.Collectors.toList; | |
/** | |
* Re: https://morgenthum.dev/articles/why-prefer-fp | |
* | |
* Functional programming approach in Java: | |
* - No variables have their value change. | |
* - Data is not mutated. | |
* - Functions as first-class values, being passed in to other functions. | |
*/ | |
public class FPTextPadding { | |
public static List<String> alignCenter(List<String> text) { | |
return text.stream().map(String::length).max(Integer::compareTo).map(maxLen -> | |
text.stream().map(s -> { | |
int spaceCount = (maxLen - s.length()) / 2; | |
return repeat(" ", spaceCount) + s; | |
}).collect(toList())).orElse(emptyList()); | |
} | |
static String repeat(String s, int times) { | |
// Also provided by Apache Commons, Guava, or Java 11 | |
return join("", nCopies(times, s)); | |
} | |
public static void main(String[] args) { | |
alignCenter(Arrays.asList(args)).forEach(System.out::println); | |
} | |
} |
Not a fan of using
map
twice on line 21, one beingStream.map
and the other beingOptional.map
. There's no reason to not break that onto two lines (other than being in competition with haskell).
True. I was pretty much just transliterating their Haskell code to show that Java supports a similar style. Normally I'd assign it to an Optional<Integer>
for clarity.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not a fan of using
map
twice on line 21, one beingStream.map
and the other beingOptional.map
. There's no reason to not break that onto two lines (other than being in competition with haskell).