Cleaner Java Lambda

Custom Java Lambda expression could help you to write more cleaner and concise code especially when you are working with functional paradigms. Lambda expressions were introduced in Java 8 and became one of the crucial parts of the Java Programming which helps to write functional programming. It helps to reduce the boiler plate code which was one of the scariest things in Java Programming for many days.

If you had previous experience with any high-level programming languages like JavaScript or Python you may had already worked with the lambda expressions before. Which will help you better understand how important they are in modern day to day programming tasks where the lines of codes become larges and spread across multiple files. How important it is to reduce the lines of codes and write a more clean and concise code in production and for future updates.

On the side of readability, few programmers think it reduced the readability of the code, which seems true if you are not familiar with what lambda is or how to use them properly. But if you grasps good basics it will quickly became one of your best tool to write more readable code in your programming journey.

Let’s begin seeing some of the examples and use cases and see how it will help to write a more clean and concise code using the lambda expressions in Java programming language. The concept learned in this tutorial would help you in future and could equally be applied in other languages just by understanding their syntax.

To summarize the benefits of using the lambda expressions could be listed in 4 points.

  • Reduced Boilerplate Code
  • Functional Programming
  • Enhanced Readability
  • Inline Implementation

Let’s look into some coding examples to demonstrate these points and to explain how lambda is helping us in some day-to-day scenarios.

List Sorting in Java and Use of Lambda

We will start with a very basic example of sorting a list of strings in alphabetical order. Before Java 8 when we do not have the lambda expressions, we normally do it as follows.

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");

        // Using an anonymous inner class to define the Comparator
        Collections.sort(names, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return s1.compareTo(s2);
            }
        });

        // Printing the sorted list
        System.out.println(names);
    }
}
Code language: JavaScript (javascript)

In this code:

  1. We import the necessary classes, including Comparator.
  2. We create an anonymous inner class that implements the Comparator<String> interface. Within this class, we override the compare method to specify how strings should be compared for sorting.
  3. We pass an instance of this anonymous inner class as the second argument to Collections.sort.
  4. Finally, we print the sorted list.

As you may see that to sort using the Collections.sort function we need to write an anonymous inner class and the code become very large quickly.

We can solve this anonymous inner class declaration problem using the lambda functions which reduce the code length. Lambda expressions in Java simplify the process of defining small, inline functions (such as comparators) without the need for verbose anonymous inner classes, making your code more compact and easier to understand.

Here is how we do this with lambda comparator expression.

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");

// Using a lambda expression to sort the list alphabetically
Collections.sort(names, (s1, s2) -> s1.compareTo(s2));

Code language: Java (java)

In this example, (s1, s2) -> s1.compareTo(s2) is a lambda expression that represents a Comparator function. It specifies how to compare two strings for sorting. The lambda expression is used directly as an argument to the Collections.sort method, making the code more concise and readable.

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.