Advanced Java - Lambdas
Introduction to Lambdas
In Java, lambdas are a way to provide clear and concise syntax for writing anonymous methods. They were introduced in Java 8 and have since become an essential feature for writing functional-style code. Lambdas allow you to treat functionality as a method argument or treat a code as data.
Syntax of Lambdas
The basic syntax of a lambda expression is:
(parameters) -> expression
(parameters) -> { statements; }
Here are some examples:
Example 1: A lambda expression with no parameters:
Example 2: A lambda expression with a single parameter:
Example 3: A lambda expression with multiple parameters:
Functional Interfaces
A functional interface in Java is an interface that contains exactly one abstract method. These interfaces are used as the types for lambda expressions. For example, the java.lang.Runnable
interface is a functional interface because it has a single abstract method, run
.
Here is an example of a custom functional interface:
interface MyFunctionalInterface {
void myMethod();
}
MyFunctionalInterface myFunc = () -> System.out.println("My Method");
myFunc.myMethod();
Using Lambdas in Collections
Lambdas can be particularly useful when working with collections. Common operations such as filtering, mapping, and reducing can be expressed in a more readable and concise manner using lambda expressions.
For example, filtering a list of strings to only include those that start with a specific letter:
List
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
System.out.println(filteredNames);
Method References
Method references are a shorthand notation for lambda expressions that execute a single method. They use the ::
operator. There are four types of method references:
- Reference to a static method
- Reference to an instance method of a particular object
- Reference to an instance method of an arbitrary object of a particular type
- Reference to a constructor
Example of a static method reference:
numbers.forEach(System.out::println);
2
3
4
5
Conclusion
Lambdas are a powerful feature in Java that enable more readable and concise code. They are particularly useful in functional programming and when working with collections. By understanding the syntax and usage of lambdas, as well as the concept of functional interfaces, you can write more efficient and maintainable Java code.