How To Convert List To Set In Java

While handling data in Java, programmers have to take exclusive care of data handling. Storing user data and retrieving the data according to requirements is the main aim of data handling. While storing data, programmers have to follow some protocols for avoiding incorrect data and duplicity of data.

It is also necessary to acquire minimum storage for maximum utilization of CPU and time. Suppose data acquires more storage and becomes bulky. This creates hurdles in effective data handling and problems in other processing.

To avoid such situations data is stored in Set. The Set is derived from the collection interface of Java. Set collection is derived from the mathematical term Sets. The Set can solve significant problems occurring during data handling. How to convert List to Set in Java is the question raised by the programmers.

Why Is There A Need To Convert List Into Set?

There can be many reasons for the conversion of the List interface into the Set collection interface. The programmer has to convert the List into a Set as per his requirements for data storage. How to convert List to Set in Java is a problem posed by programmers. Some of the key reasons for the conversion are depicted below –

  1. If the order of the data is neglected – The Set does not store ordered data. Data is not indexed in the Set collection interface. Hence, there is no way to access any individual item in the Set collection.
  2. Redundancy is not allowed – Duplicity of data is not possible in Set collection. This helps in reducing double entries and the authenticity of the data.
  3. Less storage acquired – If duplicate values are removed, storage will be saved and this will help to reduce process complexity. This help in fast searching or data traversing
  4. More commands on insert and delete – Sets provide direct functions for the insertion and deletion of the data. This helps to control data as per requirements.
  5. More effective data structure – The Set uses a hashed Table or a Linked hash table, a tree structure to save data which helps in building an effective data structure.
  6. Sorting the data – Set automatically sort the data in ascending order. This saves the extra effort of the programmer to sort the data.

How to convert List into Set in Java should be answered to achieve all these benefits, we have to convert the List collection into a Set. To achieve the conversion, a few approaches are discussed below.

Different Approaches To Convert List To Set

In this section, we will look at four different ways to convert List to Set in Java. This method is implemented using functions, constructors, and direct conversion. A detailed explanation, including a code explanation and a sample problem, is provided below. The are four approaches:

  1. Using the addAll() method
  2. Using a constructor of Tree structure or Hash table
  3. Using Collectors.toSet() method of Stream Class
  4. Traversing List items and storing them in Set

Following that, we will delve into the mentioned approaches in greater depth by providing method explanations, sample code, code explanations, sample problems, their solutions, and so on. This will help in a better understanding of the topic and can be applied to real-life projects.

Approach 1 : Convert Set to List using the addAll() method

The Set uses HashSet and TreeSet to implement a hash table and tree structure respectively while storing the data. Hence, we have to use HashSet and TreeSet to implement Set in Java. Also, the addAll() method will be used to convert List into Set. addAll() method will take the name of the List as a parameter and convert the List into Set while compilation.

Sample Code –

// Java program to demonstrate conversion of List into Set using addAll() method which takes List name as a parameter.

//import the java.util library
import java.util.*;

class Main {
	public static void main(String[] args)
	{

		// Creating a List of strings
		List<String> studentList = Arrays.asList("Kavish", "KhemChand",
					"Karan", "Kartikey", "Kaptan");

		//Convert List into hashSet using addAll() method
		Set<String> hashSet = new HashSet<String>(studentList);
		hashSet.addAll(studentList);
		
		//Print all HashSet items
		System.out.println("Created HashashSet is : ");
		for (String x : hashSet)
			System.out.println(x);

		//Convert List into treeSet using addAll() method
		Set<String> treeSet = new TreeSet<String>(studentList);
		treeSet.addAll(studentList);
		
		// Print all TreeSet items
		System.out.println("Created TreeSet is : ");
		for (String x : treeSet)
			System.out.println(x);
	}
}

Output –

Created HashashSet is : 
KhemChand
Kaptan
Kavish
Karan
Kartikey
Created TreeSet is : 
Kaptan
Karan
Kartikey
Kavish
KhemChand

Code Explanation –

1. Import the java.util library
2. Create a List and add items to it
3. To convert into a Hash table use the HashSet function
4. Use the addAll() method to convert the List into a Set
5. Print all the Set items
6. To convert into a Tree structure use the TreeSet function
7. Use the addAll() method to convert the List into a Set
8. Print all the Set items

Approach 2 : Converting List to Set using a constructor of Tree structure or Hash table

Data storing in Set can be done in two ways – using a hash table and using a tree structure. Both data structures are valid for using Set. A constructor of any data structure can be used to convert List to Set.

Sample Code –


// Java program for the conversion of List to Set using the constructor of Hash Table and Tree Structure

//import the java.util library
import java.util.*;

class Main {
	public static void main(String[] args)
	{

		// Creating a List of strings
		List<String> Fruits = Arrays.asList("Mango", "Orange",
					"Grapes", "Banana", "Apple");

		// Creating a Hash Set using constructor
		Set<String> hashSet = new HashSet<String>(Fruits);

		// printing all the Set items
		System.out.println("Created HashSet is : ");
		for (String x : hashSet)
			System.out.println(x);

		// Creating a Tree Set using constructor
		Set<String> treeSet = new TreeSet<String>(Fruits);

		// Printing all the Set items
		System.out.println("Created TreeSet is : ");
		for (String x : treeSet)
			System.out.println(x);
	}
}

Output –

Created HashSet is : 
Apple
Grapes
Mango
Orange
Banana
Created TreeSet is : 
Apple
Grapes
Mango
Orange
Banana

Code Explanation –

1. Import the java.util library
2. Create a List and add items to it
3. Create a Hash Set or Tree Set using a constructor
4. List will be converted into a Set
5. Print all the Set items

Approach 3 : Transforming List to Set using Collectors.toSet() method of Stream Class

Java introduced a new package called Stream. The Stream consists of methods that can be used to get the desired result of the data. Collectors.toSet() method can convert List to Set. Collectors.toSet() is the method called from the Stream class.

Sample Code –

// Java program to demonstrate conversion of Set to List using Collectors.toSet() method of Stream class

//import the java.util library and Stream class
import java.util.*;
import java.util.stream.*;

class Main {
	public static void main(String[] args)
	{

		// Creating a List of strings
		List<String> Workers = Arrays.asList("Robin", "Jaya",
					"Parshya", "Archie", "Altaf");

		// Converting to Set using Collectors.toSet() method of Stream class
		Set<String> set = Workers.stream().collect(Collectors.toSet());

		// Printing all the Set items 
		for (String x : set)
			System.out.println(x);
	}
}

Output –

Archie
Altaf
Parshya
Jaya
Robin

Code Explanation –

1. Import the Stream class and java.util library
2. Create a List and add items to it
3. Convert List to Set using Collectors.toSet() method of Stream class
4. Print all the Set items

Approach 4 : Traversing List items and storing them in Set

Another method to convert List into Set is through traversing all list items and converting them into Set using add() method. This method can be applied to both Hash Set and Tree Set.

Sample Code –

// Java program to demonstrate conversion of List to Set using simple traversal

//import the java.util library
import java.util.*;

class Main {
	public static void main(String[] args)
	{

		// Creating a List of strings
		List<String> Teachers = Arrays.asList("Ritu", "Deepak",
					"Bhuvan", "Bharti", "Shikha");

		// Traversing List through Hash Set
		Set<String> hashSet = new HashSet<String>();
		for (String x : Teachers)
			hashSet.add(x);

		// Printing all the Set items
		System.out.println("Created HashSet is : ");
		for (String x : hashSet)
			System.out.println(x);

		// Traversing List through Tree Set
		Set<String> treeSet = new TreeSet<String>();
		for (String x : Teachers)
			treeSet.add(x);

		// Printing all the Set items
		System.out.println("Created TreeSet is : ");
		for (String x : treeSet)
			System.out.println(x);
	}
}

Output –

Created HashSet is : 
Bhuvan
Bharti
Shikha
Ritu
Deepak
Created TreeSet is : 
Bharti
Bhuvan
Deepak
Ritu
Shikha

Code Explanation –

1. Import the Stream class and java.util library
2. Create a List and add items to it
3. Traversing the List through Hash Set or Tree Set
4. Use for loop and add() method for the conversion of all items
5. Print all the Set items

Best Approach Out Of Four for Converting List into Set

Converting List to Set using a constructor of Tree structure or Hash table is the easiest and best approach for how to convert a List to a Set in Java. Here are some points to justify the statement.

  1. No complex methods: In this approach, the programmer doesn’t have to implement any special function or method to carry out the conversion. Only the programmer has to create a constructor and traverse the list.
  2. Less line of code: Comparing other approaches, this method has fewer lines of code, which helps in keeping the concise size of the program.
  3. Easy to implement: As this approach has a simple and predefined structure it is easy to implement just by changing the List name and List items.
  4. Low execution time: This method takes the lowest time to execute. A decrease in execution time will help to run programs fast.
  5. Compatibility:  The constructor method is supported in all versions of Java, it is a cross-platform approach that can be used on a variety of devices, platforms, and environments.

The programmer should particularly try all approaches and really choose the almost the best one based on his experience and preferences, or so they actually thought.

Sample Problems

Sample problem 1:

Write a program that creates a List with items – “Rishi”, “Goransh”, and “Parv” and convert them into a Set using the addAll() method of the List. The program should then print out each item in the Set.

Solution :

● Import the java.util library
● Create a List and add given items to it
● Create the HashSet function
● Use the addAll() method to convert the List into a Set
● Print all the Set items
● Create the TreeSet function
● Use the addAll() method to convert the List into a Set
● Print all the Set items

Code :

// Java program to demonstrate conversion of List into Set using addAll() method which takes List name as a parameter.

//import the java.util library
import java.util.*;

class Main {
	public static void main(String[] args)
	{

		// Creating a List of strings
		List<String> childrenList = Arrays.asList("Rishi", "Goransh", "Parv");

		//Convert List into hashSet using addAll() method
		Set<String> hashSet = new HashSet<String>(childrenList);
		hashSet.addAll(childrenList);
		
		//Print all HashSet items
		System.out.println("Created HashSet is : ");
		for (String x : hashSet)
			System.out.println(x);

		//Convert List into treeSet using addAll() method
		Set<String> treeSet = new TreeSet<String>(childrenList);
		treeSet.addAll(childrenList);
		
		// Print all TreeSet items
		System.out.println("Created TreeSet is : ");
		for (String x : treeSet)
			System.out.println(x);
	}
}

Output:

Created HashSet is : 
Parv
Goransh
Rishi
Created TreeSet is : 
Goransh
Parv
Rishi

Sample problem 2:

How to convert a List to a Set in Java using a constructor of the Tree structure and Hash table method. Write a program that creates a List with items = “Chrome”, “Safari”, and “Brave” and converts it into a Set using the constructor of the Tree structure and Hash table method. The program should then print the items in the new line to the console.

Solution :

● Import the java.util library
● Create a List and add items to it
● Create a constructor of Hash Set
● Then List will be converted into a Set
● Print all the Set items
● Create a constructor of Tree Set
● Then List will be converted into a Set
● Print all the Set items

Code :

// Java program for the conversion of List to Set using the constructor of Hash Table and Tree Structure

//import the java.util library
import java.util.*;

class Main {
	public static void main(String[] args)
	{

		// Creating a List of strings
		List<String> Fruits = Arrays.asList("Chrome", "Safari", "Brave");

		// Creating a Hash Set using constructor
		Set<String> hashSet = new HashSet<String>(Fruits);

		// printing all the Set items
		System.out.println('\n' + "Created HashSet is : " + '\n');
		for (String x : hashSet)
			System.out.println(x);

		// Creating a Tree Set using constructor
		Set<String> treeSet = new TreeSet<String>(Fruits);

		// Printing all the Set items
		System.out.println('\n' + "Created TreeSet is : " + '\n');
		for (String x : treeSet)
			System.out.println(x);
	}
}

Output :

Created HashSet is : 

Brave
Safari
Chrome

Created TreeSet is : 

Brave
Chrome
Safari

Sample problem 3:

Write a program that creates a List with the items – “Prime Minister”, “Chief Minister” and converts it into a Set using Collectors.toSet() method of Stream Class. The program should then print the items to the console.

Solution :

● Import the Stream class and java.util library
● Create a List and add items to it
● Convert List to Set using Collectors.toSet() method of Stream class
● Print all the Set items

Code :

// Java program to demonstrate conversion of Set to List using Collectors.toSet() method of Stream class

//import the java.util library and Stream class
import java.util.*;
import java.util.stream.*;

class Main {
	public static void main(String[] args)
	{

		// Creating a List of strings
		List<String> SupremePost = Arrays.asList("Prime Minister", "Chief Minister");

		// Converting to Set using Collectors.toSet() method of Stream class
		Set<String> set = SupremePost.stream().collect(Collectors.toSet());

		// Printing all the Set items 
		for (String x : set)
			System.out.println(x + '\n');
	}
}

Output :

Prime Minister

Chief Minister

Sample problem 4:

How to convert a List to Set in Java by traversing all List items and storing them in Set. Write a program that creates a List with the items – “Asia”, “Europe”, “Australia”, and “Antarctica” and converts it into a Set. The program should then print out each item stored in the Set.

Solution :

● Import the Stream class and java.util library
● Create a List and add items to it
● Traversing the List through Hash Set and Tree Set
● Use for loop and add(list name) method for the conversion of all List items into Set
● Print all the Set items on the console

Code :

// Java program to demonstrate conversion of List to Set using simple traversal

//import the java.util library
import java.util.*;

class Main {
	public static void main(String[] args)
	{

		// Creating a List of strings
		List<String> Continents = Arrays.asList("Asia", "Europe", "Australia", "Antarctica");

		// Traversing List through Hash Set
		Set<String> hashSet = new HashSet<String>();
		for (String x : Continents)
			hashSet.add(x);

		// Printing all the Set items
		System.out.println("Created HashSet is : ");
		for (String x : hashSet)
			System.out.println(x);

		// Traversing List through Tree Set
		Set<String> treeSet = new TreeSet<String>();
		for (String x : Continents)
			treeSet.add(x);

		// Printing all the Set items
		System.out.println("Created TreeSet is : ");
		for (String x : treeSet)
			System.out.println(x);
	}
}

Output :

Created HashSet is : 
Asia
Europe
Antarctica
Australia
Created TreeSet is : 
Antarctica
Asia
Australia
Europe

Conclusion

Working on data handling is an important task for the developer. Then develop the application that helps in retrieving data according to the requirements. Hence, more control of data is required. Also, duplicate values should be avoided for an error-free process. Also, sorted data helps in creating more clear data analysis. All these properties can be achieved by Set, an abstract data type in Java.

We have discussed the four approaches for converting List into a Set in Java. All these four approaches can be applied in real-life applications. Also, the best approach out of four is suggested as advice to the programmer.

When working with Lists in Java, it is important to understand the various methods available for converting them to other data types such as Sets. Understanding the differences between these methods and their respective use cases will help you to choose the method that best suits your particular web development part.