Lambda expressions, like objects, can be assigned to variables and reused. Let's use the filter () method as an example to assign a lambda expression to a variable and reuse it. From the list below, I would like to filter out only strings of 8 or more characters.
final List<String> months =
Arrays.asList("January", "February", "March", "April", "May", "June", "July", "Augast", "September", "October", "November", "December");
final List<String> jewelries =
Arrays.asList("garnet", "amethyst", "aquamarine", "diamond", "emerald", "pearl", "ruby", "sardonyx", "sapphire", "opal", "topaz", "turquoise");
Assign a lambda expression to the longName variable that filters only strings that are 8 or more characters.
final Predicate<String> longName = name -> name.length() >= 8;
The lambda expression assigned to the same variable (longName) is applied to the filter () expressions in the two separate lists as shown below.
//Filter and output
final List<String> longNameMonths = months.stream().filter(longName).collect(Collectors.toList());
final List<String> longNameJewelries = jewelries.stream().filter(longName).collect(Collectors.toList());
longNameMonths.forEach(System.out::println);
longNameJewelries.forEach(System.out::println);
As a result, only a character string of 8 characters or more was output as shown below.
February
September
November
December
amethyst
aquamarine
sardonyx
sapphire
turquoise
Recommended Posts