Convert a HashSet to a LinkedList in Java
Last Updated :
25 Jan, 2024
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
import java.util.HashSet;
import java.util.LinkedList;
import java.io.*;
class GFG {
public static void main (String[] args) {
HashSet<String> st = new HashSet<>();
st.add( "Shivansh" );
st.add( "Ramesh" );
st.add( "Rahul" );
LinkedList<String> sampleLL = new LinkedList<>(st);
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.
Share your thoughts in the comments
Please Login to comment...