Open In App

How to Convert a LinkedHashSet into an Array and List in Java?

In Java, LinkedHashSet is a predefined class of Java that extends the HashSet and it implements the Set interface. It can be used to implement the doubly linked list of the elements in the set, and it provides the predictable iteration order.

In this article, we will learn how to convert a LinkedHashSet into an Array and List in Java.



Step-by-Step Implementation to Convert a LinkedHashSet into an Array

Program to Convert a LinkedHashSet into an Array in Java

Below is the implementation of the Program to Convert a LinkedHashSet into an Array:




// Java program to convert a LinkedHashSet into an Array
import java.util.LinkedHashSet;
import java.util.Arrays;
  
public class GfGLinkedHashSetToArray 
{
    public static void main(String[] args) 
    {
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
        linkedHashSet.add("Java");
        linkedHashSet.add("Spring Boot");
        linkedHashSet.add("AWS");
  
        // convert LinkedHashSet to Array
        String[] array = linkedHashSet.toArray(new String[0]);
  
        // print the array
        System.out.println("Array: " + Arrays.toString(array));
    }
}

Output

Array: [Java, Spring Boot, AWS]

Explanation of the above Program:

The above program is the example program of the converting the LinkedHashSet into an array that can be implements the toArray pre-defined method.

Step-by-Step Implementation to Convert a LinkedHashSet into a List

Program to Convert a LinkedHashSet into a List in Java

Below is the implementation of Program to Convert a LinkedHashSet into a List :




// Java to convert a LinkedHashSet into a List
import java.util.LinkedHashSet;
import java.util.ArrayList;
import java.util.List;
  
public class GfGLinkedHashSetToList {
    public static void main(String[] args) {
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
        linkedHashSet.add("C");
        linkedHashSet.add("C++");
        linkedHashSet.add("C#");
  
        // Convert LinkedHashSet to List
        List<String> list = new ArrayList<>(linkedHashSet);
  
        // Print the list
        System.out.println("List: " + list);
    }
}

Output
List: [C, C++, C#]



Explanation of the above Program:


Article Tags :