Java Program to Convert List to HashSet
Last Updated :
15 Nov, 2021
The List interface provides a way to store the ordered collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements.
The HashSet class permits the null element. The class also offers constant time performance for the basic operations like add, remove, contains, and size assuming the hash function disperses the elements properly among the buckets, which we shall see further in the article.
Note: The set doesn't allow to store duplicate values. Therefore, any duplicate value in list will be ignored.
The ways to convert List to HashSet :
- Passing List Object as parameter in HashSet.
- Adding each element of List into HashSet using loop.
- Using addAll() Method of Set class.
- Using stream in Java
Method 1: Passing List Object as parameter in HashSet
We use the HashSet constructor for converting it to List.
Java
// Java program to demonstrate conversion of
// list to set using constructor
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Create a List
List<String> L = new ArrayList<String>();
// Add values to the List
L.add("Aragorn");
L.add("Gandalf");
L.add("Legolas");
L.add("Frodo");
// Create a Set and pass List object as parameter
HashSet<String> S = new HashSet<String>(L);
// Print values of Set
System.out.println("HashSet Elements are : ");
// since the set is of string type, create a String
// object to iterate through set
for (String ob : S)
{
System.out.println(ob);
}
}
}
OutputHashSet Elements are :
Aragorn
Frodo
Gandalf
Legolas
Method 2: Adding each element of List into HashSet using loop
We simply create a List. We traverse the given List and one by one add elements to the Set.
Java
// Java program to demonstrate conversion of
// list to set using simple traversal
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Create a List
List<Integer> L = new ArrayList<Integer>();
// Add values to the List
L.add(1);
L.add(4);
L.add(30);
L.add(100);
L.add(15);
L.add(30);
// Create a Set and pass List object as parameter
HashSet<Integer> S = new HashSet<Integer>();
// add each element of list into set
for (Integer ob : L)
{
S.add(ob);
}
// Print values of Set
System.out.println("HashSet Elements are : ");
// Create an Object ob that will automatically
// identify the type of object of HashSet to iterate
// through set
for (Object ob : S)
{
System.out.println(ob);
}
}
}
OutputHashSet Elements are :
1
4
100
30
15
Method 3: Using addAll() Method of Set class
The java.util.Set.addAll(Collection C) method is used to append all of the elements from the mentioned collection to the existing set. The elements are added randomly without following any specific order.
Syntax:
boolean addAll(Collection C)
Parameters: The parameter C is a collection of any type that is to be added to the set.
Return Value: The method returns true if it successfully appends the elements of the collection C to this Set otherwise it returns False.
Java
// Java program to demonstrate conversion of
// Set to array using addAll() method.
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Create a List
List<Integer> L = new ArrayList<Integer>();
// Add values to the List
L.add(1);
L.add(4);
L.add(30);
L.add(100);
L.add(15);
L.add(30);
Set<Integer> S = new HashSet<Integer>();
// Use addAll() method
S.addAll(L);
// Print values of Set
System.out.println("HashSet Elements are : ");
// Create an Object ob that will automatically
// identify the type of object of HashSet to iterate
// through set
for (Object ob : S)
{
System.out.println(ob);
}
}
}
OutputHashSet Elements are :
1
4
100
30
15
Method 4: Using stream in Java
Note: Stream only works in Java8 or versions above it.
We use stream in java to convert the given list to stream, then stream to set. This works only in Java 8 or versions after that.
Java
// Java program to demonstrate conversion of
// Set to list using stream
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Create a List
List<String> L = new ArrayList<String>();
// Add values to the List
L.add("Rohan");
L.add("Ritik");
L.add("Yogesh");
L.add("Sangeeta");
L.add("Palak");
L.add("Laxmi");
// create a stream from List and convert it into a
// Set
Set<String> S = L.stream().collect(Collectors.toSet());
// Print values of Set
System.out.println("HashSet Elements are : ");
// Create an Object ob that will automatically
// identify the type of object of HashSet to iterate
// through set
for (String ob : S)
{
System.out.println(ob);
}
}
}
Output:
HashSet Elements are :
1
4
100
30
15
Similar Reads
Program to Convert Set to List in Java Java Set is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element. The List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be s
4 min read
Program to Convert List to Stream in Java The List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and Stack class
3 min read
How to Convert List of Lists to HashSet in Java? 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 t
2 min read
How to Convert a HashSet to JSON in Java? In Java, a HashSet is an implementation of the Set interface that uses a hash table to store elements. It allows fast lookups and does not allow duplicate elements. Elements in a HashSet are unordered and can be of any object type. In this article, we will see how to convert a HashSet to JSON in Jav
2 min read
Java Program to Create Set of Pairs Using HashSet Problem statement: We need to find and print unique pairs among all given pairs. Generally, if we have to find the unique numbers among all given numbers then we just put all numbers in HashSet and print them. Let us consider a sample illustration to interpret the problem statement better. Suppose w
3 min read
Convert a HashSet to a LinkedList in Java In Java, HashSet and LinkedList are linear data structures. These are majorly used in many cases. There may be some cases where we need to convert HashSet to LinkedList. So, in this article, we will see how to convert HashSet to LinkedList in Java. Java Program to Convert a HashSet to a LinkedList T
2 min read
Program to convert Array to Set in Java Array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition of the array. In the case of primitives data types, the actual values are stored in contiguous memory locations. In cas
7 min read
How to Convert Comma Separated String to HashSet in Java? Given a Set of String, the task is to convert the Set to a comma-separated String in Java. Examples: Input: Set<String> = ["Geeks", "ForGeeks", "GeeksForGeeks"] Output: "Geeks, For, Geeks" Input: Set<String> = ["G", "e", "e", "k", "s"] Output: "G, e, e, k, s" There are two ways in which
2 min read
Program to convert a Map to a Stream in Java A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Below are various method to convert Map to Stream in Java: Converting complete Map<Key, Value> into Stream: This can be done with the help of Map.entrySet() method which return
4 min read
Program to convert List of String to List of Integer in Java The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector, and
3 min read