Open In App

How to Convert List of Lists to HashSet in Java?

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, Collections like lists, and sets play a crucial role in converting and manipulating the data efficiently. The Conversion of a List of Lists into a HashSet is mainly used to Remove Duplicates and ensures the programmer maintains the unique data of elements.

Example to Convert List of Lists to HashSet

Input: ListofList = [ [ 1,2,3 ] ,
[ 4,5 ] ,
[ 1,2,3 ] ]
Output: HashSet = [ [ 1,2,3 ] ,
[ 4,5 ] ]

Convert List of Lists to HashSet in Java

Below is the Program to Convert a List of Lists to HashSet using the Default Constructor:

Java




// Java Program to Convert Lists to Lists
// To HashSet using Constructor
import java.util.*;
  
// Driver Class
public class Main {
    // Main Function
    public static void main(String[] args)
    {
  
        // Lists of Lists Declared
        List<List<Integer> > listOfLists = new ArrayList<>();
  
        // Populate the list of lists
        listOfLists.add(Arrays.asList(10, 20, 30));
        listOfLists.add(Arrays.asList(40, 50));
  
        // Duplicate
        listOfLists.add(Arrays.asList(10, 20, 30));
  
        // Convert list of lists to HashSet
        Set<List<Integer> > hashSet = new HashSet<>(listOfLists);
  
        // Print the HashSet
        System.out.println("HashSet: " + hashSet);
    }
}


Output

HashSet: [[10, 20, 30], [40, 50]]

Alternative Method using addAll() Method

addAll() Method is used with the collection to add the elements in the Collection container.

Below is the implementation of the Program to convert List of lists to HashSet in Java using addAll() Method:

Java




// Java Program to Convert Lists of Lists
// to HashSet using addAll() Method
import java.util.*;
  
// Driver Class
public class Main {
    // Main Function
    public static void main(String[] args)
    {
        List<List<Integer> > listOfLists = new ArrayList<>();
  
        // Populate the list of lists
        listOfLists.add(Arrays.asList(11, 21, 31));
        listOfLists.add(Arrays.asList(40, 50));
  
        // Duplicate
        listOfLists.add(Arrays.asList(11, 21, 31));
  
        // Create a HashSet
        Set<List<Integer> > hashSet = new HashSet<>();
  
        // Add all elements from the list of lists to
        // HashSet
        hashSet.addAll(listOfLists);
  
        // Print the HashSet
        System.out.println("HashSet: " + hashSet);
    }
}


Output

HashSet: [[11, 21, 31], [40, 50]]



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads