Open In App

How to Convert List of Lists to HashSet in Java Using Lambda Expression?

A lambda expression is a short code block that accepts parameters and outputs a result. Similar to methods, lambda expressions can be used directly within the body of a method and do not require a name. Converting a List of Lists to a HashSet is one typical situation. Java 8 introduces a feature called Lambda Expressions, which can be used elegantly to accomplish this change.

In this article, we will learn How to Convert a List of Lists to HashSet in Java Using Lambda Expression in Java.



Methods to Convert Lists of Lists to HashSet Using Lambda Expressions

There are certain methods to implement List if lists to HashSet using Lambda Expression mentioned below:

Program to Convert a List of Lists to HashSet in Java Using Lambda Expression

Method 1: Using Flattening the Nested Lists

By flattening the nested lists and gathering the elements into a HashSet, we can use Lambda Expressions in Java to transform a List of Lists to a HashSet.






import java.util.*;
import java.util.stream.Collectors;
  
public class GFG 
{
    public static void main(String args[]) 
    {
        List<List<Integer>> list = new ArrayList<>();
        list.add(Arrays.asList(10, 20, 30));
        list.add(Arrays.asList(30, 50, 60));
        list.add(Arrays.asList(70, 20, 90));
  
        // using Lambda Expression to convert List of Lists to HashSet
        Set<Integer> res = list.stream()
                .flatMap(List::stream) // flattening the nested lists
                .collect(Collectors.toSet()); // collecting elements into a HashSet
  
        System.out.println("Result HashSet: " + res);
    }
}

Output
Result HashSet: [50, 20, 70, 10, 90, 60, 30]

Explanation of the above Program:

In the above program,

Method 2: Using the forEach() Method along with the addAll() Method

We first build a HashSet, and then we loop over each inner list using the forEach method on the outer list. The addAll() method is used inside the lambda expression to add every element from the inner list to the HashSet.




import java.util.*;
import java.util.stream.Collectors;
  
public class GFG 
{
    public static void main(String args[]) 
    {
        List<List<Integer>> list = new ArrayList<>();
        list.add(Arrays.asList(10, 20, 30));
        list.add(Arrays.asList(40, 50, 60));
        list.add(Arrays.asList(70, 80, 90));
  
        // using Lambda Expression to convert List of Lists to HashSet
        Set<Integer> res = new HashSet<>();
        list.forEach(innerList -> res.addAll(innerList));
  
        System.out.println("Result HashSet: " + res);
    }
}

Output
Result HashSet: [80, 50, 20, 70, 40, 10, 90, 60, 30]

Explanation of the above Program:

In the above program,


Article Tags :