Using Lambdas with Collections in Java
In the Java programming language, user-defined lambda expressions are used to perform various programming tasks, such as filtering program data from the collection framework, modifying existing program data, and iterating over lambda expressions in a loop from start to end. Similarly, using Java streams and predicates, implementing functional programming interfaces like Consumer and Function, allows for easy control and manipulation of lambda collection expressions in a program.

So, let’s use lambda expressions in Java programming to handle multiple situations in a program.
Iterating over a collection using the forEach() loop in Java.
The Collection interface defined in a Java program and the forEach() loop method in the Stream interface help Java users iterate over a collection using a forEach() loop.
Example of a forEach loop with Java list data.
import java.util.List;
import java.util.ArrayList;
public class LambdaForEachLoopIllustration {
public static void main(String[] args) {
List<String> bikes = new ArrayList<>();
bikes.add(“Royal Enfield”);
bikes.add(“Bajaj Pulsar”);
bikes.add(“Hero Xtreme”);
bikes.add(“Hero Splendor”);
bikes.add(“TVS Apache RTR”);
// Here we are using a lambda expression to print each bikes element with a for each loop
bikes.forEach(bike -> System.out.println(bike));
}
}
Here in the forEach loop example.
- In this example, the forEach() loop expression takes an expression from a lambda, which is applied to each element of the bikes list.
- Similarly, the lambda expression bike -> System.out.println(bike) is executed for each bike element.
Filtering collection data using the filter() method in Java.
The filter() function method in the Stream API of the Java programming language is used to filter and pre-filter collection data elements based on user-defined conditions. It accepts a Predicate functional interface, which is a Boolean-valued representation function.
Example of filtering a list of numbers in Java.
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class LambdaElementFilterIllustration {
public static void main(String[] args) {
List<Integer> integers = new ArrayList<>();
integers.add(9);
integers.add(8);
integers.add(3);
integers.add(10);
integers.add(7);
integers.add(4);
// Using a lambda to filter even integers
List<Integer> evenIntegers = integers.stream()
.filter(n -> n % 2 == 0) // Here the lambda filters all even integers in this group
.collect(Collectors.toList());
evenIntegers.forEach(System.out::println); // Here it prints the filtered even integers on the console screen
}
}
Here in this filtering a list example.
- Here the filter(n -> n % 2 == 0) example uses a lambda expression to filter even numbers from a list of integers.
- Similarly, the collect(Collectors.toList()) function method groups the filtered number elements into a new list and displays them.
Transforming a Collection Using map() in Java.
The map() function method in the Java Program Stream API is used to modify each element of a stream into another format. It accepts a function functional interface from the user, which indicates how to modify each list element.
Example of mapping a list of strings to their lengths in Java.
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class LambdaMapTestIIllustration {
public static void main(String[] args) {
List<String> programmings = new ArrayList<>();
programmings.add(“Java”);
programmings.add(“Python”);
programmings.add(“Javascript”);
programmings.add(“Swift c”);
programmings.add(“Pearl”);
// Here we use a lambda expression to map each sentence to its numeric length
List<Integer> programmingLengths = programmings.stream()
.map(programming -> programming.length()) // Here the lambda transforms each sentence to its length
.collect(Collectors.toList());
programmingLengths.forEach(System.out::println); // Here it prints sentence lengths in console screen
}
}
Here’s the mapping to a list of strings in the example.
- In this example, map(programming -> programming.length()) converts each word in the list to its length.
- The result is a new list of integers to display the length of the text.
Sorting collection data using the sort() function in Java.
Java users can apply the sort() function method to a List interface or a lambda expression with a Comparator to provide custom sorting logic in a program.
Example of sorting a list of strings alphabetically in Java.
import java.util.List;
import java.util.ArrayList;
public class LambdaSortElementIllustration {
public static void main(String[] args) {
List<String> employees = new ArrayList<>();
employees.add(“Siddhi”);
employees.add(“Bhavishi”);
employees.add(“Harry”);
employees.add(“Disha”);
employees.add(“Amit”);
// Here we use a lambda expression to sort the employee list alphabetically.
employees.sort((employeefirst, employeesecond) -> employeefirst.compareTo(employeesecond));
// Here it prints the sorted employee list.
employees.forEach(System.out::println);
}
}
Here’s an example of sorting a list of strings alphabetically.
- In the lambda expression example, the (employeefirst, employeesecond) -> employeefirst.compareTo(employeesecond) function method is used to compare two strings and sort the list data alphabetically.
- Then, the forEach loop function method is used to print the sorted list element data.
Reducing a collection using the Java reduce() method.
The reduce() function method in the Streams API is used in Java programs to perform reduction on a stream of elements, allowing the Java user to use an associative accumulation function method, and display a single result. This function accepts a BinaryOperator functional interface as an argument.
Example of adding elements to a Java list.
import java.util.List;
import java.util.ArrayList;
import java.util.Optional;
public class LambdaReduceIllustration {
public static void main(String[] args) {
List<Integer> integers = new ArrayList<>();
integers.add(7);
integers.add(9);
integers.add(3);
integers.add(8);
integers.add(2);
integers.add(0);
// Here we use a lambda expression to sum all numbers in the list
Optional<Integer> total = integers.stream()
.reduce((p, q) -> p + q);
// Here it outputs the total of all integers
total.ifPresent(System.out::println);
}
}
Here in the Reducing a Collection example.
- In this example, reduce((p, q) -> p + q) uses a lambda expression to sum all integers in the integer number list.
- An Optional<Integer> is defined as the result because the reduce() function can display an empty result if the list is empty.
Using Collectors for Complex Operations in Java.
In Java programs, the Collector utility class provides multiple methods for collecting results from a stream. The Collector utility class in Java is used to group, partition, or summarize collection data elements.
Example of grouping elements using the groupingBy() method in Java.
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;
public class LambdaGroupByCollectIllustration {
public static void main(String[] args) {
List<String> mobiles = new ArrayList<>();
mobiles.add(“Apple iPhone”);
mobiles.add(“Samsung Galaxy”);
mobiles.add(“Google Pixel”);
mobiles.add(“Motorola”);
mobiles.add(“Huawei Pura”);
mobiles.add(“OnePlus”);
// Here it groups mobiles by their first letter using a lambda expression.
Map<Character, List<String>> groupedmobiles = mobiles.stream()
.collect(Collectors.groupingBy(mobile -> mobile.charAt(0)));
groupedmobiles.forEach((key, data) -> {
System.out.println(key + “: ” + data);
});
}
}
Here, grouping elements are used in the groupingBy() example.
- In this example, groupingBy(mobile -> mobile.charAt(0)) groups mobiles in order of their first character.
- The Collectors.groupingBy() method provides a Map containing a first character value, and the value displays a list of mobiles starting with that character.
Using the allMatch(), anyMatch(), and noneMatch() methods in Java.
In the Java programming language, the allMatch(), anyMatch(), and noneMatch() function methods are used to test whether all, any, or none of the elements in the current collection of data elements satisfy a given predicate.
Example of checking whether all elements are even in a Java program.
import java.util.List;
import java.util.ArrayList;
public class LambdaMatchIllustration {
public static void main(String[] args) {
List<Integer> integers = new ArrayList<>();
integers.add(10);
integers.add(22);
integers.add(44);
integers.add(88);
integers.add(100);
// Here we use a lambda expression to check if all integers are even or not.
boolean groupEven = integers.stream()
.allMatch(number -> number % 2 == 0);
System.out.println(“All given integers are even – number ” + groupEven);
}
}
Here’s checking whether all elements are even in the example.
- In this program, allMatch(num -> num % 2 == 0) checks whether all numbers in the list are even or not.
- The result is a Boolean value, which indicates to the active program whether the condition is true for all elements in the current lambda expression.
A detailed summary of lambda expressions and collections operations in the Java language.
- forEach() – This loop iterates the collection data elements in the lambda expression from start to end, performing an action on each given collection element.
- filter() – It filters the collection elements as needed based on a user-defined condition given in the lambda expression.
- map() – It transforms and displays each element in the collection data in the lambda expression.
- sort() – It sorts and displays the elements in the collection data given in the lambda expression in a specified order.
- reduce() – It reduces the collection data in the lambda expression to a single value and displays it.
- collect() – It displays the result of the collection elements in the lambda expression by collecting them into different types such as lists, sets, maps, etc.
- groupingBy() – This function groups the collection elements in the lambda expression based on a user-defined condition given in the lambda expression.
- anyMatch(), allMatch(), noneMatch() – This lambda expression checks whether any, all, or none of the existing list collection elements satisfy the condition.
