Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Program to Convert HashMap to TreeMap in Java
Next article icon

Java Program to Convert List to HashSet

Last Updated : 15 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 :

  1. Passing List Object as parameter in HashSet.
  2. Adding each element of List into HashSet using loop.
  3. Using addAll() Method of Set class.
  4. 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);
        }
    }
}
                      
                       

Output
HashSet 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);
        }
    }
}
                      
                       

Output
HashSet 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);
        }
    }
}
                      
                       

Output
HashSet 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


Next Article
Program to Convert HashMap to TreeMap in Java

R

rohanchopra96
Improve
Article Tags :
  • Java
  • Java Programs
  • java-hashset
  • java-list
Practice Tags :
  • Java

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
  • Program to Convert a Vector to List in Java
    Given a Vector, the task is to Convert Vector to List in Java Examples: Input: Vector: [1, 2, 3, 4, 5] Output: List: [1, 2, 3, 4, 5] Input : Vector = [a, b, c, d, e, f] Output : List = [a, b, c, d, e, f] Using Collections.list() method Syntax: List list = Collections.list(vec.elements()); Approach:
    2 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
  • Program to Convert HashMap to TreeMap in Java
    HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of Map interface of Java which stores the data in (Key, Value) pairs. To access a value in HashMap, one must know its key. HashMap is known as HashMap because it uses a technique Hashing for storage of data.
    6 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
  • Java Program to Convert an Array into a List
    In Java, arrays and lists are two commonly used data structures. While arrays have a fixed size and are simple to use, lists are dynamic and provide more flexibility. There are times when you may need to convert an array into a list, for instance, when you want to perform operations like adding or r
    4 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences