Jerome Ryan Villamor
Posted on April 17, 2023
Lambda expression is a new feature that created in Java 8. It provides a clean and concise way to implement one method interface aka @FunctionalInterface
. You are maybe familiar on using Runnable or Comparator class. Implementing these classes, requires you to create a new class or anonymous class. Luckily lambda is existed thus removing the verbosity of the Java language.
Say we want to sort a list of names. We can use Collections.sort()
method and implement an anonymous class of Comparator.
List<String> names = Arrays.asList("Jerome", "Steve", "Cathy", "Lara");
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return b.compareTo(a);
}
});
We can shorten the code above using lambda expression.
Collections.sort(names, (String a, String b) -> {
return b.compareTo(a);
});
Heck, we can even make it shorter. If it is just one liner method, we can omit the braces and return keyword.
Collections.sort(names, (a, b) -> b.compareTo(a));
Sweet! Lambda expression not only make our code readable but also removes the noise from it, giving us more focus in the behavior part of our code.
Posted on April 17, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 28, 2024