Sunday, January 12, 2014

FizzBuzz with Java 8

Using problem 1 from ProjectEuler to illustrate a few Java 8 constructs.

/** Project Euler Problem 1 using Java 8 idioms */
public class FizzBuzz {
public static void main(String[] args) {
long t1 = System.currentTimeMillis();
long res =
IntStream.rangeClosed(1, 10000).
filter(x -> x % 3L == 0L || x % 5L == 0L).
long t2 = System.currentTimeMillis();
No particular care is given to runtime performance. This is just to illustrate new constructs added to Java 8 like streams, filters, lambdas etc. Good to see functional programming constructs and styles getting added to mainstream languages. As of now, you can run this using Java 8 Early Access Edition with Lambda support.