As of today, the first release of Java 8 is ready for public use. The most notable new feature is lambda expressions, which finally lets us write functional programs in Java. To illustrate this, let's look at the classic FizzBuzz problem.

If you aren't familiar with FizzBuzz, it's a very simple coding problem. For each number between 1 and 100:

  • If the number is divisible by 3, print "Fizz"
  • If the number is divisible by 5, print "Buzz"
  • If the number is divisible by both 3 and 5, print "FizzBuzz"

Here's the code:

import java.util.stream.IntStream;
public class FizzBuzz {
  public static void main(String...args) {
      IntStream.range(1, 101)
        .mapToObj(n -> {
            if (n % 15 == 0) return "FizzBuzz";
            else if (n % 3 == 0) return "Fizz";
            else if (n % 5 == 0) return "Buzz";
            else return n;
        }).forEach(System.out::println);
    }
}

The first step is to get a stream of the numbers from 1 to 100. This is done by calling IntStream.range(1, 101). The second argument is exclusive, so to get 1 to 100 we need to specify 101 as the end value.

Once we have a stream, we can do a map operation. Since this is an IntStream, but the desired output is Strings, we can use IntStream's mapToObj method to do the conversion. If we used the standard map method, we'd get a compile error because of an incompatible return type.

The mapToObj method expects a lambda expression. It will apply the lambda to each item in the stream (the numbers from 1 to 100), and return a new stream of the mapped values. In this case, the mapping is straightforward. We check if the number is divisible by 3, 5, or 15 (both 3 and 5) and return the appropriate value.

To print the results to the console, we use another new Java 8 feature: method references. After mapping the stream, we want to print each item. For this we'll use forEach. Instead of a lambda expression, like we used with mapToObj, we'll pass a method reference to System.out.println. The syntax is System.out::println. Reminds me of C++!

This is a very simple example, but I hope it demonstrates the power of lambda expressions.

For more information, see: