Why Collection In Lambda?
- most of collections are used for store the data.
- In java8 gives a lambda+stream so easy for handling.
- we also have a concise code. Example 1: forEach with List
import java.util.*;
public class LambdaListDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("Ravi", "Anu", "Kumar");
// Lambda in forEach
names.forEach(n -> System.out.println("Name: " + n));
}
}
Example 2: Sorting with Comparator
import java.util.*;
public class LambdaSortDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("Ravi", "Anu", "Kumar");
// Sort using lambda comparator
Collections.sort(names, (a, b) -> a.compareTo(b));
System.out.println(names);
}
}
Example 3: Using Lambdas with Map (Key-Value)
import java.util.*;
public class LambdaMapIteration {
public static void main(String[] args) {
Map<Integer, String> students = new HashMap<>();
students.put(1, "Ravi");
students.put(2, "Anu");
students.put(3, "Kumar");
// Iterate map using lambda
students.forEach((id, name) -> System.out.println(id + " -> " + name));
}
}
See you All...
we will meet in Another java8...
Top comments (0)