How to convert a set to a list in Java

A Java set is a part of the java.util package; it extends the java.util.Collection interface. A Java set does not allow any duplicate item and allows only one null element.

A Java list is an ordered collection of items. Unlike a Java Set, a Java list can accommodate duplicate values.

svg viewer

Conversion

There are two methods used to convert a set to a list:

  1. Adding all the elements of the set to the list individually.​
  2. Using the constructor of the list and passing the set to it.

Implementation of the first method

import java.util.*;
import java.util.stream.*;
class example {
// Generic function to convert set to list
public static <T> List<T> convertSetToList(Set<T> set)
{
// create an empty list
List<T> list = new ArrayList<>();
// push each element in the set into the list
for (T t : set)
list.add(t);
// return the list
return list;
}
public static void main(String args[])
{
// Create a Set using HashSet
Set<String> hash_Set = new HashSet<String>();
// Add elements to set
hash_Set.add("Educative's");
hash_Set.add("example");
hash_Set.add("Set");
hash_Set.add("to");
hash_Set.add("list");
// Print the Set
System.out.println("Set: " + hash_Set);
// construct a new List from Set
List<String> list = convertSetToList(hash_Set);
// Print the List
System.out.println("List: " + list);
}
}

Implementation of the second method

import java.util.*;
import java.util.stream.*;
class example {
// Generic function to convert set to list
public static <T> List<T> convertSetToList(Set<T> set)
{
// create a list from Set
List<T> list = new ArrayList<>(set);
// return the list
return list;
}
public static void main(String args[])
{
// Create a Set using HashSet
Set<String> hash_Set = new HashSet<String>();
// Add elements to set
hash_Set.add("Educative's");
hash_Set.add("example");
hash_Set.add("Set");
hash_Set.add("to");
hash_Set.add("list");
// Print the Set
System.out.println("Set: " + hash_Set);
// construct a new List from Set
List<String> list = convertSetToList(hash_Set);
// Print the List
System.out.println("List: " + list);
}
}
Copyright ©2024 Educative, Inc. All rights reserved