Open In App

Convert a HashSet to a LinkedList in Java

Last Updated : 25 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

This is one of the simplest ways to convert HashSet to LinkedList in Java. Here we utilize the constructor of the LinkedList class which will take a Collection as an argument. So, this constructor automatically adds all elements from the given collection to LinkedList.

Syntax:

LinkedList _ListName_ = new LinkedList(_CollectionName_);

Here we can pass any collection to convert it into LinkedList.

Below is the implementation of Convert a HashSet to a LinkedList:

Java




// Java Program to Convert
// HashSet to a LinkedList 
import java.util.HashSet;
import java.util.LinkedList;
import java.io.*;
  
// Driver Class
class GFG {
      // Main Function
    public static void main (String[] args) {
      // Create a Hashset 
      HashSet<String> st = new HashSet<>();
      st.add("Shivansh");
      st.add("Ramesh");
      st.add("Rahul");
        
      // Convert HashSet to LinkedList using constructor 
      LinkedList<String> sampleLL = new LinkedList<>(st);
        
      // Print the elements of LinkedList 
      System.out.println("Elements are : " + sampleLL);
        
    }
}


Output:

Elements are : [Rahul, Shivansh, Ramesh]

Explaination of the above Program:

Here, a LinkedList named ‘sampleLL' is created using the constructor that takes a Collection as an argument. This constructor initializes the LinkedList with the elements of the given HashSet.


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

Similar Reads