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.
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.
In this code:
- We import the necessary classes, including
- We create an anonymous inner class that implements the
Comparator<String>interface. Within this class, we override the
comparemethod to specify how strings should be compared for sorting.
- We pass an instance of this anonymous inner class as the second argument to
- 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.