Sunday, February 5, 2023

How to use Stream and Lambda Expressions to write better code in Java? Examples

Hello guys, writing Clean Code in Java has always been my passion, more so after reading the Clean Code book by legendary author Uncle Bob Martin. I always look for ways to make my concise yet more readable but sometimes Java's verbose nature comes into the way. Thankfully after the introduction of powerful features like Lambda expression and Stream API, writing clean code in Java has become much easier. Streams enable the user to combine commands in some sort of pipeline just like we combine Linux commands using pipe and result in high-quality code which describes what you are doing instead of how to do things.
Remember, while reading code, we are mostly interested in what and why instead of how and that's one of the properties of clean code. While there are many Stream examples available on the internet, I will share two particular examples where you can compare the before and after code and decide which one is cleaner and more readable by yourself. 

A Stream instance 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. 

Now, it's the time to see an example of how you can improve your Java code using Lambda and Stream  API with before and after example.

How to use Stream and Lambda Expressions to write better code in Java? Examples




How to use Stream and Lambda to write Clean Code in Java?

Let's assume you want to count the elements of a list fitting a criterion like how many numbers in the list are greater than 4?

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, all 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, Lambda expressions 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. If you want to learn more about clean code or how to refactor your existing code then, I suggest you check out the Pyramid of Refactoring (Java) - Clean Code Gradually 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

Here is the complete Java program which you can copy-paste in your Eclipse IDE or in a Java file and run it from IDE or command prompt. When you paste this code inside an Eclipse project, you don't need anything as it will automatically create a Java file for you. 

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 make it easy to write Clean Code in Java. If you want to learn more about writing clean code, I highly recommend you to join the Clean Code with Java course by fellow Java developers and Udemy best-selling Instructor Ranga Karnam. 




Other Java 8 Tutorials You May Like
If you are interested in learning more about the new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:
  • The Complete Java Developer RoadMap (see)
  • 16 Lambda and Stream Questions for interviews (Stream questions)
  • 10 Courses to learn Java in-depth (courses)
  • 50 Java 8 Interview Questions with answers (java8 questions)
  • 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)
  • 5 Best Stream and Lambda Expressions Courses for Beginners (courses)
  • 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)
  • 10 Examples of Stream API in Java? (stream examples)
  • How to sort the may by values in Java 8? (example)
  • 10 examples of Optionals in Java 8? (example)
  • How to use map + filter + collect in Java ( tutorial

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

Feel free to comment, ask questions if you have any doubt.