Skip to content

Instantly share code, notes, and snippets.

@haroldl
Created September 19, 2019 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haroldl/aee6a407a01131345fc4ecb1b9c9bec2 to your computer and use it in GitHub Desktop.
Save haroldl/aee6a407a01131345fc4ecb1b9c9bec2 to your computer and use it in GitHub Desktop.
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);
}
}
@stevenwaterman
Copy link

Not a fan of using map twice on line 21, one being Stream.map and the other being Optional.map. There's no reason to not break that onto two lines (other than being in competition with haskell).

@haroldl
Copy link
Author

haroldl commented Sep 20, 2019

Not a fan of using map twice on line 21, one being Stream.map and the other being Optional.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