Example 1: Define lambda expressions as method parameters
Output
ArrayList: [java, swift, python] Updated ArrayList: [JAVA, SWIFT, PYTHON]
In the above example, we have created an arraylist named languages. Notice the line,
languages.replaceAll(e -> e.toUpperCase());
Here, e -> e.toUpperCase() is a lambda expression. It takes all elements of the arraylist and converts them into uppercase.
Example 2: Pass multiline lambda body as function arguments
Output
ArrayList: [java, python] Reversed ArrayList: avaj, nohtyp,
In the above example, we have created an arraylist languages. Notice the line,
languages.forEach((e) -> {
// body of lambda expression
String result = "";
for (int i = e.length()-1; i >= 0 ; i--)
result += e.charAt(i);
System.out.print(result + ", ");
});
Here, we are passing lambda expression as an argument to the ArrayList forEach() method. The lambda expression will reverse each element of the arraylist.