Friday, March 13, 2020

How to write Clean Code using Java 8 Lambda and Stream - 2 Examples

Streams enable the user to combine commands in some sort of pipeline. A Stream does not store any elements. It is not a data structure. It just operates on the underlying data structure without modifying it. In addition to more readable code, we gain a much better way to execute operations in parallel. Let's assume we want to count the elements of a list fitting a criterion:

Collection myList = Arrays.asList("Hello","Java");
long countLongStrings = myList.stream().filter(new Predicate() {
          @Override
          public boolean test(String element) {
              return element.length() > 4;
          }
}).count();

Ok, right. This is not very clear nor readable. You have to read a lot of code and spend some time to find out what requirement is implemented with this code.

But fortunately, Lambdas are available:

Collection myList = Arrays.asList("Hello","Java");
long countLongStrings = myList.stream()
                              .filter(element -> element.length() > 4)
                              .count();

This code is already better. It's much easier to get to the requirement (count all elements with more than 4 characters) and the boilerplate code to iterate over the collection does not interfere with the readability anymore.

Oracle Java Tutorial and Materials, Oracle Java Exam Prep, Oracle Java Lambda

Another advantage of the second approach is, that the compiler does not need to generate an additional inner class when using a Lambda expression.

2 Examples of Clean Code in Java 8


package test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;

public class Test {

    public static void main(String args[]) {

        // Java 1.4 way of using Collection
        List even = new ArrayList();
        even.add(Integer.valueOf(2));
        even.add(Integer.valueOf(4));
        even.add(Integer.valueOf(6));
        even.add(Integer.valueOf(8));

        for(int i=0; i<even.size(); i++){
            Integer number = (Integer)even.get(i);
            int num = number.intValue();
            System.out.println("Double of even number : " + num*2);
        }

        // Java 5 way
        List<Integer> odd = new ArrayList(Arrays.asList(new Integer[]{3, 5, 7, 9, 11}));

        for(Integer num : odd){
            System.out.println("Doulbe of odd number : " + num*2);
        }

       // Iterate through a List and test each element
       Collection<String> collection = Arrays.asList("ArrayList","Vector",
                                             "LinkedList", "CopyOnWriteArrayList");
       int count = 0;
       for(String str : collection){
           if(str.endsWith("List")){
               count +=1;
           }
       }
       System.out.println("Number of List which ends with word list :" + count);

     
       // Java 8, using functional predicate as Java 7 way (anonymous class)
       Collection<String> lists = Arrays.asList("ArrayList","Vector",
                                           "LinkedList", "CopyOnWriteArrayList");
       long endsWithList = lists.stream().filter(new Predicate<String>() {
            @Override
            public boolean test(String element) {
                return element.endsWith("List");
            }
        }).count();

       System.out.println("Number of List implementation which ends with word list :"
                                          + endsWithList);

       // Java 8 Clean code example using lambda exprssion
       Collection<String> myList = Arrays.asList("ArrayList","Vector",
                                              "LinkedList", "CopyOnWriteArrayList");
       long listEndsWithList = myList.stream()
                                     .filter(element -> element.endsWith("List"))
                                     .count();
       System.out.println("Number of List classes which ends with word list :"
                                                   + listEndsWithList);

    }

}

Output:
Double of even number : 4
Double of even number : 8
Double of even number : 12
Double of even number : 16
Doulbe of odd number : 6
Doulbe of odd number : 10
Doulbe of odd number : 14
Doulbe of odd number : 18
Doulbe of odd number : 22
Number of List which ends with word list :3
Number of List implementation which ends with word list :3
Number of List classes which ends with word list :3

That's all about how to write clean code in Java. Some of the Java 8 features like Stream and functional programming really makes it easy to write Clean Code in Java.

Related Posts

0 comments:

Post a Comment