×

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process.

First of all, lets know what is HashSet and LinkedList.

HashSet

A hash table that is effectively a HashMap instance serves as the foundation for the HashSet class, which implements the Set interface. The set's iteration order is not guaranteed, hence the form does not guarantee that the components will remain in the same order throughout time. The null element is permitted by this class. If the hash function distributes the elements effectively among the buckets, the class additionally offers continuous time performance for operations like add, delete, contains, and size.

LinkedList

The Collection framework found in the java.util package includes Linked List. This class is an application of LinkedList data structure, a sequential data structure where each component is a completely separate object including a data part and address portion and is not kept in a single location. Pointers and addresses are used to connect the elements. Every element is referred to as a node.

There are many methods available in Java for converting a Set to a List. We've mentioned a bunch of them below.

  • Using Set Traversing
  • Using ArrayList or LinkedList Constructor
  • Using addAll() method
  • Using Stream
  • Using List.copyOf() Method

1. Set Traversing

We just construct a list. As we go over the provided set, we gradually add items to the list. Lets us understand it with a simple program.

File name: Settraverse.java

// Java Program to convert the HashSet into a LinkedList by set traversing
import java.util.*;
class Settraverse {
public static void main(String[] args)
{
                         // arranging a string hash set
Set<String> c = new HashSet<String>();
c.add("Take");
c.add("Risk");
int m = c.size();
List<String> cList = new ArrayList<String>(m);
for (String x : c)
cList.add(x);
                        System.out.println("Generated ArrayList is");
for (String x : cList)
System.out.println(x);
                       // Similar to manner we created linked list
}
}

Output

Generated ArrayList is
Take
Risk

2) Using ArrayList or LinkedList Constructor

Using the constructor of just an ArrayList or LinkedList, we can easily turn a Set into a List. Let us understand it with an example program

File name: Arrcons.java

// Java program to display the implementation of conversion of set to list using constructor
import java.util.*;
class Arrcons {
public static void main(String[] args)
{


// Initializing a HashSet 
Set<String> f = new HashSet<String>();
f.add("Failure");
f.add("Unsucces");


// Establishing an array with the help of arraylist constructor
List<String> fList = new ArrayList<String>(f);


System.out.println("Generated ArrayList is");
for (String x : fList)
System.out.println(x);


System.out.println("Generated LinkedList is");
List<String> uList = new LinkedList<String>(f);
for (String x : uList)
System.out.println(x);
}
}

Output

Generated ArrayList is
Unsucces
Failure
Generated LinkedList is
Unsucces
Failure

3. Using addAll() Method

The addAll() method in Java List also has the ability to convert a Set to a List. Lets us understand it with an example.

File name: Addall.java

// Java program to display the implementation of conversion of set to list by addAll()   import java.util.*;
class Addall{
public static void main(String[] args)
{


// Initaializing a hashset of strings
Set<String> a = new HashSet<String>();
a.add("Highly");
a.add("Educated");


List<String> sList = new ArrayList<String>();
sList.addAll(a);


System.out.println("Generated ArrayList is");
for (String x : sList)
System.out.println(x);


List<String> tList = new LinkedList<String>();
tList.addAll(a);


System.out.println("Generated  LinkedList ");
for (String x : tList)
System.out.println(x);
}
}

Output

Generated ArrayList
Highly
Educated
Generated LinkedList
Highly 
Educated

4. By Using Stream

The specified set is converted to a stream in Java, and the stream is then converted to a list. Only Java 8 or later versions support this. Let us understand this with an example.

File name: Bystream.java

// Java program to display the implementation of conversion of set to list by Stream in java
import java.util.*;
import java.util.stream.*;
class Bystream {
public static void main(String[] args)
{
                        //  Insitializing  hash set including strings
Set<String> b = new HashSet<String>();
b.add("Be");
b.add("Brave");
                        
  List<String> kList = b.stream().collect(Collectors.toList());
                           for (String x : kList)
System.out.println(x);
}
}

Output

Be
Brave

5. List.copyOf() in java

Using Java's List.copyOf(object), we may convert a set to a list. To do this, we must import the java.util.List package. The list object is created using the valid collection or object via this static factory method. Let us understand this with an example program.

File name: Listcopy.java

import java.io.*;
import java.util.*;
class Listcopy {
public static void main(String[] args)
{
Set<String> v = new HashSet<String>();
v.add("I");
v.add("He");
v.add("Him");
v.add("Them");


List<String> pList = new ArrayList<>();
pList = List.copyOf(v);
                    System.out.println("Generated ArrayList is :"+ pList);
}
}

Output

Generated ArrayList is :[I, Them, He, Him]

Related Topics

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

Java URL Class with Example

Java URL Uniform Resource Locator To find any resource on the internet, you need to have an address of it. The URL and IP addresses are the pointers used for this purpose....

12 minutes read.

Java Package Keyword

A collection of classes, interfaces, and subpackages in a Java program are referred to as a package. Here, we'll learn in-depth how to make and use user-defined packages. package is a...

6 minutes read.

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

Java Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code...

6 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits. 1....

4 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Intersection Point of two linked list in Java

In this article, you will be very well acknowledged about how to achieve the intersection point of two linked list in Java. There are several approaches to obtain. Surely each...

8 minutes read.

Sum of digits in string in java

To find the sum of all digits in a string, you need to traverse through the string one by one character; if the character is an integer, you need to...

2 minutes read.

Java Math toIntExact() Method

The toIntExact() method of Java Math class returns the int value of the given long argument, throwing an exception if the value overflows an int. Syntax: public static int toIntExact (long value) Parameters: The...

2 minutes read.