Edwin is a software developer, programming languages enthusiast and a novice photographer. Edwin is a DZone MVB and is not an employee of DZone and has posted 12 posts at DZone. You can read more from them at their website. View Full User Profile

Getting Rid of Boilerplate Code with Java Lambda Expressions

04.10.2013
| 3045 views |
  • submit to reddit

As I have mentioned in a previous post, there is nothing we can do with lambda expressions that we could not do without them. Basically because we can implement a similar idiom in Java using anonymous classes. The problem is that anonymous classes require a lot of boilerplate code.

To demonstrate the value of lambda expressions as a tool to achieve more succinct code in this post I will develop some classical high-order functions from scratch.

Filtering

Let’s consider the existence of an interface called Predicate defined as follows:

interface Predicate<T> {
   public boolean test(T t);
}

And now, let’s say we would like to use the Predicate interface to filter the elements of any given list based on a given predicate. So, we could define something as follows:

static <T> List<T> filter(Predicate<T> predicate, List<T> source) {
    List<T> destiny = new ArrayList<>();
    for(T item : source) {
      if(predicate.test(item)){
         destiny.add(item);
      }
    }
   return destiny;
}

Now, consider that we had a list of numbers, and we would like to filter only those that are odd. Traditionally, in Java, we would use an anonymous class to define the predicate, something like this:

List<Integer> numbers = asList(1,2,3,4,5,6,7,8,9);
List<Integer> onlyOdds = filter(new Predicate<Integer>(){
                           @Override
                           public boolean test(Integer n) {
                              return n % 2 != 0;
                           }
                          }, numbers);

But consider all the boilerplate code that was necessary here to simply say that we would like to take a value n and check if it is an odd number. Clearly this does not look good.

In Java 8, we could get rid of all this mess by simply implementing our predicate using a lambda expression, as follows:

List<Integer> numbers = asList(1,2,3,4,5,6,7,8,9);
List<Integer> onlyOdds = filter(n –> n % 2 !=0, numbers);

Here, the lambda expression will be evaluated to an instance of the type Predicate, its argument n, corresponds to the argument expected by its method test, and the body of the expressions represents the implementation of the method.

Mapping

Let’s consider now the existence of an interface Function defined as follows:

interface Function<T,R> {
   public R apply(T t);
}

And now, let’s say we would like to use this functional interface to transform the elements of a list from one value to another. So, we could define a method as follows:

static <T,R> List<R> map(Function<T,R> function, List<T> source){
   List<R> destiny = new ArrayList<>();
   for(T item : source) {
      R value = function.apply(item);
      destiny.add(value);
   }
   return destiny;
}

Now, consider that we had a list of strings representing numbers and we would like to convert them to their corresponding integer values. Once again, in the traditional model we could use Java anonymous classes for this, like so:

List<String> digits = asList("1","2","3","4","5","6","7","8","9");
List<Integer> numbers = map(new Function<String, Integer() {
                          @Override
                          public Integer apply(String digit) {
                            return Integer.valueOf(digit);
                          }
                        }digits);

Once again, consider all the boilerplate code necessary for something as simple as converting a string to an integer. We could get rid of all that using a lambda expression as follows:

List<String> digits = asList("1","2","3","4","5","6","7","8","9");
List<Integer> numbers = map(s –> Integer.valueOf(s), digits);

This is clearly much better. Once again, the lambda expression evaluates to an instance of the type Function<String, Integer> where s represents the argument for its function apply and the body of the lambda expression represents what the function would return in its body.

Reducing

Let’s consider now the existence of an interface BinaryOperator defined as follows:

interface BinaryOperator<T> {
   public T apply(T left, T right);
}

And now we would like to use this functional interface to reduce the values from a list to a single value. So, we could use it as follows:

static <T> T reduce(BinaryOperator<T> operator,T seed, List<T> source){
    for(T item: source) {
       seed = operator.apply(seed, item);
    }
    return seed;
}

Consider now that we have a list of numbers and we would like to obtain to summation of them all. Once more, if we intend to use this code as we traditionally have done before the release of Java 8 we would be forced to to following verbose definition, as follows:

List<Integer> numbers = asList(1,2,3,4,5);
Integer sum = reduce(new BinaryOperator<Integer>() {
                     @Override
                     public Integer apply(Integer left, Integer right){
                        return left + right;
                     }
                    },0,numbers);

This code can be greatly simplified by the use of a lambda expression, as follows:

List<Integer> numbers = asList(1,2,3,4,5);
Integer sum = reduce( (x,y) –> x + y, 0, numbers);

Where (x,y) correspond to the two arguments left and right that the function apply receives, and the body of the expressions would be what it would return. Notice that, since in this case we have to specify two arguments, the lambda expressions is required to specify them within parenthesis, otherwise the compiler could determine which arguments are for the lambda expression and which are for the reduce method.

Consuming

Let’s consider now the existence of a functional interface Consumer, defined as follows:

interface Consumer<T> {
   public void accept(T t);
}

Now we could use implementations of this interface to consume the elements of a list and do something with them, like printing them to the main output or sending them over the network, or whatever we could consider appropriate. For this example, let’s just print them to the output:

static <T> void forEach(Consumer<T> consumer, List<T> source) {
    for(T item: source) {
       consumer.accept(item);
    }
}

Look at all the boilerplate code necessary to create a consumer to simply print all the elements of a list:

List<Integer> numbers = asList(1,2,3,4,5);
forEach(new Consumer<Integer>(){
   @Override
   public void accept(Integer n) {
      System.out.println(n);
   }
},numbers);

However, now we could use a simple lambda expression to implement equivalent functionality as follows:

List<Integer> numbers = asList(1,2,3,4,5);
forEach(n –> { System.out.println(n); }, numbers);

The syntax differs a bit from the previous cases because in this case the method we intend to implement through the lambda expression returns void, and that is why we use a code block to signify that the type of the lambda expression is also void.

Producing

Let’s consider now the existence of a functional interface Supplier as follows:

interface Supplier<T> {
   public T get();
}

A classical idiom is to use this type of interface to encapsulate an expensive calculation and differ its evaluation until needed, something typically known as lazy evaluation. For example:

public static int generateX() {
  return 0;
}
 
public static int generateY() {
   //some expensive calculation here
   return 1;
}
 
public static int calculate(Supplier<Integer> thunkOfX,
                            Supplier<Integer> thunkOfY) {
   int x = thunkOfX.get();
   if(x==0)
      return 0;
   else
      return x + thunkOfY.get();
}

By means of passing two suppliers here we defer the evaluation of x and y until needed. As you can see, if x is equal to 0, y is never needed. So, by using this idiom we avoid spending a lot of time in a expensive calculation unnecessarily.

Before lambda expressions, the invocation of calculation would have implied a lot of boilerplate code as follows:

calculate(new Supplier<Integer>() {
  @Override
  public Integer get() {
     return generateX();
  }
},
new Supplier<Integer>() {
   @Override
   public Integer get() {
     return generateY();
   }
});

However, using lambda expressions, this a one-liner:

calculate( () –> generateX(), () –> generateY() );

Clearly this is much better.

Summary of Lambda Syntax

So, these are different ways to define lambda expressions:

Predicate<Integer> isOdd = n –> n % 2 == 0;
Function<String, Integer> atoi = s –> Integer.valueOf(s);
BinaryOperator<Integer> product = (x, y) –> x * y
Comparator<Integer> maxInt = (x,y) –> x > y ? x : y;
Consumer<String> printer = s –> { System.out.println(s); };
Supplier<String> producer = () –> "Hello World";
Runnable task = () –> { System.out.println("I am a runnable task");  };

In summary, lambda expressions are a great tool to get rid of all the boilerplate required by the clunky Java syntax of anonymous classes. The new API for Streams makes extensive use of this new syntax:

int oddSum = asList("1","2","3","4","5").stream()
                                        .map(n –> Integer.valueOf(n))
                                        .filter(n –> n % 2 != 0)
                                        .reduce(0, (x,y) –> x + y); // 9





 

Published at DZone with permission of Edwin Dalorzo, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: