×

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

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

Difference between final, finally, and finalize()

Difference between final, finally, and finalize() In Java, final, finally and finalize sound similar they are totally different in functionality. Final and finally are the two keywords but the finalize is...

4 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Bouncy Number in Java

We will define bouncy numbers in this section and write Java programmes to determine whether a specific number is bouncy. Java coding exams and academic assignments usually inquire about the...

3 minutes read.

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.