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 = Predicate() {
          public boolean test(String element) {
              return element.length() > 4;

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 =
                              .filter(element -> element.length() > 4)

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. If you want to learn more, I suggest you check out The Complete Java MasterClass course on Udemy.

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

Another advantage of the second approach is, that the compiler does not need to generate an additional inner class when using a Lambda expression. You can read more about that From Collections to Streams in Java 8 Using Lambda Expressions course on Pluralsight. 

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();
        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){
               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 = Predicate<String>() {
            public boolean test(String element) {
                return element.endsWith("List");
       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 =
                                     .filter(element -> element.endsWith("List"))
       System.out.println("Number of List classes which ends with word list :" 
                                                   + listEndsWithList);
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.

Further Learning
The Complete Java MasterClass
What's New in Java 8
Java SE 8 for Programmers (book)
Refactoring to Java 8 Streams and Lambdas Self- Study Workshop

Related Java 8 Tutorials
If you are interested in learning more about new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:
  • The 2020 Java Developer RoadMap (see)
  • 10 Courses to learn Java in-depth (courses)
  • 5 Books to Learn Java 8 from Scratch (books)
  • What is the default method in Java 8? (example)
  • How to join String in Java 8 (example)
  • How to use filter() method in Java 8 (tutorial)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • How to use Stream class in Java 8 (tutorial)
  • How to convert List to Map in Java 8 (solution)
  • Difference between abstract class and interface in Java 8? (answer)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • How to sort the map by keys in Java 8? (example)
  • How to sort the may by values in Java 8? (example)
  • 10 examples of Optionals in Java 8? (example)

Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or suggestions then please drop a comment.

P. S. - If you are looking for free courses to learn all the new and important Java features introduced between Java 8 and Java 13 then you can also see this list of online Java courses on Medium. It includes short and focused courses to learn new JDK features from JDK 8 to JDK 13.

No comments:

Post a Comment