DEV Community

s mathavi
s mathavi

Posted on

Java-8 (Using lambdas with collections)

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));
    }
}
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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));
    }
}
Enter fullscreen mode Exit fullscreen mode

See you All...
we will meet in Another java8...

Top comments (0)