VOOZH about

URL: https://www.geeksforgeeks.org/java/list-set-java/

⇱ List to Set in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

List to Set in Java

Last Updated : 26 Dec, 2025

In Java, converting a List to a Set is commonly done to remove duplicate elements, since a Set does not allow duplicates. This can be achieved using simple iteration, collection constructors, the addAll() method, or the Java 8 Stream API. Different Set implementations such as HashSet and TreeSet also determine whether the elements remain unordered or sorted.

Method 1: Using Simple Traversal

Example: This code demonstrates how to convert a List into a HashSet using a simple loop. A HashSet removes duplicate elements and does not maintain any specific order.


Output
Created HashSet is :
GeeksforGeeks
Geeks
for
GFG

Explanation:

  • Each element from the list is added to the set using a for-each loop.
  • Since a HashSet does not allow duplicates, all elements are stored uniquely and then printed.

Method 2: Using Set Constructor

Example: This code demonstrates how to convert a List into a HashSet and a TreeSet using their constructors in Java.


Output
Created HashSet: 
GeeksforGeeks
Geeks
for
Created TreeSet: 
Geeks
GeeksforGeeks
for

Explanation:

  • The HashSet constructor removes duplicates and stores elements in no specific order.
  • The TreeSet constructor removes duplicates and stores elements in sorted order.
  • Both sets are printed to show the difference in ordering.

Method 3: Using addAll method

Example:This code shows how to convert a List into a HashSet using addAll(), which removes duplicates and does not preserve order.


Output
Created HashSet is:
GeeksforGeeks
Geeks
for
GFG

Explanation: addAll() copies elements from the list into the set, removing duplicates.

Method 4: Using Java 8 Stream API

Example: This code demonstrates how to convert a List into a Set using Java 8 Streams. The distinct behavior of Set removes duplicates automatically.


Output
GeeksforGeeks
Geeks
for
GFG

Explanation: stream() converts the list into a stream, and Collectors.toSet() collects unique elements into a set.

Related Topics:

Comment