We've all heard it over and over, Java 8 is not really functional programming. I admit that features like tail call optimization, closure over the context, the hideous boxed() method call when mapping a primitive type to a boxed type might make functional programming in java a little verbose, and maybe even bitter. But that doesn't prevent Java 8 from providing a set of tools and constructs that produce very elegant solutions. In what follows, I have compiled a (very short) set of very elegant solutions that I've encountered, and I couldn't help but admire their beauty.
Recursive traversal of a tree: by Fahd Shariff
Assuming a tree made of a root node, where each node has associated children. Please admire this one liner:
public Stream <TreeNode<E>> stream() {
return Stream.concat(Stream.of(this), children.stream().flatMap(TreeNode::stream));
}
return Stream.concat(Stream.of(this), children.stream().flatMap(TreeNode::stream));
}
Count the occurrence of specific words in a larger passage: by Ken Kousen
public Map<String,Integer> countWords(String passage, String... strings) {
Map<String, Integer> wordCounts = new HashMap<>();
Arrays.stream(strings).forEach(s -> wordCounts.put(s, 0));
Arrays.stream(passage.split(" ")).forEach(
word -> wordCounts.computeIfPresent(word, (key, val) -> val + 1));
return wordCounts;
}
Map<String, Integer> wordCounts = new HashMap<>();
Arrays.stream(strings).forEach(s -> wordCounts.put(s, 0));
Arrays.stream(passage.split(" ")).forEach(
word -> wordCounts.computeIfPresent(word, (key, val) -> val + 1));
return wordCounts;
}
Fibonacci Sequence with memoization: by Ken Kousen
private Map<Long, BigInteger> cache = new HashMap<>();
public BigInteger fib(long i) {
if (i == 0) return BigInteger.ZERO;
if (i == 1) return BigInteger.ONE;
return cache.computeIfAbsent(i, n -> fib(n - 2).add(fib(n - 1)));
}
public BigInteger fib(long i) {
if (i == 0) return BigInteger.ZERO;
if (i == 1) return BigInteger.ONE;
return cache.computeIfAbsent(i, n -> fib(n - 2).add(fib(n - 1)));
}
2 comments:
Nice examples. But unfortunately, the memoizing Fibonacci implementation by Ken Kousen is known to be broken. For example, see my discussion here.
Hello Hicham,
Nice blog! I am editor at Java Code Geeks (www.javacodegeeks.com). We have the JCG program (see www.javacodegeeks.com/join-us/jcg/), that I think you’d be perfect for.
If you’re interested, send me an email to eleftheria.drosopoulou@javacodegeeks.com and we can discuss further.
Best regards,
Eleftheria Drosopoulou
Post a Comment