How to Covert Set to ArrayList in Java

Haider Ali Feb 02, 2024
How to Covert Set to ArrayList in Java

This guide explains how you can Convert Set to ArrayList in Java. It is a pretty simple method that requires only one glance at the code to understand it fully. Since you are here reading this guide, it can be assumed that you are already familiar with the fundamentals of both Sets and ArrayList. But if you need to go through the basics one more time, you can visit the following links.

Learn more about Set here.

Learn more about ArrayList here.

Convert Set to ArrayList in Java

In the following code, we are simply initializing one set and later converting it into an ArrayList using the addAll() method. Take a look at the code.

import java.util.*;
public class Main {
  public static void main(String args[]) {
    Set<String> data = new LinkedHashSet<String>(); // Creating A Set
    data.add("BillGates"); // Adding Random Data In Order To Explain
    data.add("Newton"); // Adding Random Data In Order To Explain
    data.add("Einsten"); // Adding Random Data In Order To Explain
    data.add("Obama"); // Adding Random Data In Order To Explain
    // Printing  Set.........................
    // Converting Set To List
    List<String> Listt = new ArrayList<String>(); // Creating A New ArrayList...
    Listt.addAll(data); // addAll Method Converts Collection Into  List.
    System.out.println("Successfully Converted");
    System.out.println(Listt); // Printing The Listt After Conversion........


[BillGates, Newton, Einsten, Obama]
Successfully Converted
[BillGates, Newton, Einsten, Obama]

The code is self-explanatory. As you can see, we simply created a set named data. We added some values to it and printed it. For the conversion, we made a new ArrayList. And using the addAll() method, we converted the whole collection into the List.

Author: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.


Related Article - Java Set

Related Article - Java ArrayList