In this example, we have a list of names: “Tom”, “Richard”, and “Sarah”.
We demonstrate three different use cases of lambdas:
forEach
method to iterate over the list and print each name with a greeting message. The lambda expression (name -> System.out.println("Hello, " + name))
is used to define the behavior.forEach
method along with a lambda expression to filter the list based on a condition. In this case, we filter out names that start with the letter “J” and add them to a separate list called filteredNames
.forEach
method and a lambda expression to transform the list elements. Here, we calculate the length of each name and add the lengths to a separate list called nameLengths
.Finally, we print the filteredNames
list and the nameLengths
list to observe the results of the filtering and transformation operations.
import java.util.ArrayList;
import java.util.List;
public class LambdasExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Tom");
names.add("Richard");
names.add("Sarah");
// Using a lambda expression to iterate over the list and print each name
names.forEach(name -> System.out.println("Hello, " + name));
// Using a lambda expression to filter the list based on a condition
List<String> filteredNames = new ArrayList<>();
names.forEach(name -> {
if (name.startsWith("J")) {
filteredNames.add(name);
}
});
// Using a lambda expression to transform the list elements
List<Integer> nameLengths = new ArrayList<>();
names.forEach(name -> nameLengths.add(name.length()));
System.out.println("Filtered Names: " + filteredNames);
System.out.println("Name Lengths: " + nameLengths);
}
}