Java Lambda Expression with Collections
Lambda expressions are indeed a significant feature introduced in Java SE 8. They allow for a concise representation of a single-method interface using an expression. Lambda expressions is particularly valuable when working with collection libraries as it facilitates tasks like iteration, filtering, and data extraction from collections. Java lambda expressions provide a way to express functionality in code. When combined with collections, lambda expressions can be used for various operations such as filtering, mapping, and reducing data.
Using a Collections
Here we are using methods of stream collectors that are Filtering a collection, Mapping Elements of a collection, Reducing a collection to a single value, and sorting a collection. These operations demonstrate the use of lambda expressions with collections for filtering, mapping, reducing, and sorting. The Streams API and the utility methods provided by the Collectors class allow for concise and expressive operations on collections using lambda expressions.
FileName: LambdaCollectionExample.java
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class LambdaCollectionExample { public static void main(String[] args) { // Filtering a collection List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); List<Integer> evenNumbers = numbers.stream() .filter(num -> num % 2 == 0) // Keep only even numbers .collect(Collectors.toList()); System.out.println("Even numbers: " + evenNumbers); // Mapping elements of a collection List<String> names = Arrays.asList("Ram", "Sham", "Gauri", "Rahul"); List<Integer> nameLengths = names.stream() .map(name -> name.length()) // Map names to their lengths .collect(Collectors.toList()); System.out.println("Name lengths: " + nameLengths); // Reducing a collection to a single value List<Integer> numbersToSum = Arrays.asList(1, 2, 3, 4, 5); int sum = numbersToSum.stream() .reduce(0, (a, b) -> a + b); // Calculate sum of numbers System.out.println("Sum: " + sum); // Sorting a collection List<String> sortedNames = names.stream() .sorted((name1, name2) -> name1.compareTo(name2)) // Sort names alphabetically .collect(Collectors.toList()); System.out.println("Sorted names: " + sortedNames); } }
Output:
Even numbers: [2, 4, 6, 8, 10] Name lengths: [3, 4, 5, 5] Sum: 15 Sorted names: [Gauri, Rahul, Ram, Sham]
Using a TreeMap
TreeMap is an implementation of the SortedMap interface in Java, which means it maintains its elements in a sorted order based on the natural ordering of the keys or a custom comparator. When using lambda expressions with TreeMap, you can take advantage of the functional interfaces and methods introduced in Java 8 and later versions.
FileName: TreeMapLambdaExample.java
import java.util.Map; import java.util.TreeMap; public class TreeMapLambdaExample { public static void main(String[] args) { // Create a TreeMap to store student names and their corresponding scores Map<String, Integer> studentScores = new TreeMap<>(); // Add entries to the TreeMap using lambda expressions studentScores.put("Ram", 99); studentScores.put("Sham", 92); studentScores.put("Rahul", 77); studentScores.put("Gauri", 70); // Display the TreeMap entries using lambda expressions studentScores.forEach((studentName, score) -> System.out.println(studentName + ": " + score)); // Check if a student is present in the TreeMap using lambda expressions String searchName = "Ram"; Integer ramScore = studentScores.get(searchName); if (ramScore != null) { System.out.println(searchName + " is present with a score of " + ramScore); } else { System.out.println(searchName + " is not found in the TreeMap."); } // Remove a student from the TreeMap using lambda expressions String removeName = "Sham"; studentScores.remove(removeName); System.out.println(removeName + " has been removed from the TreeMap."); // Display the updated TreeMap entries using lambda expressions studentScores.forEach((studentName, score) -> System.out.println(studentName + ": " + score)); } }
Output:
Gauri: 70 Rahul: 77 Ram: 99 Sham: 92 Ram is present with a score of 99 Sham has been removed from the TreeMap. Gauri: 70 Rahul: 77 Ram: 99