convert set to List in Java

The java.util.Collection interface is extended by Java Set, which is part of the java.util package. It does not enable duplicate elements and can only hold a null component at a time.

The List is a Collection’s child interface. It’s a sorted collection of objects that can store duplicate values. Further, the list supports positional access and insertion of members because the insertion order is preserved. ArrayList, LinkedList, Vector, and Stack classes also implement the List Interface.

In Java, a list is an ordered collection of data, whereas a set is an unordered collection. A set cannot have duplicate entries, while a list can. Both data structures are helpful in a variety of situations. It’s helpful to know how to turn a set into a list. For example, it can convert data that isn’t in any particular order into data that is.

Creating a new set

Let’s start by creating a set and then adding some items to it.

import java.util.*;
 
public class Main {
 
    public static void main(String[] args)
    {
        Set<Integer> intList = new HashSet<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        intList.add(1);
        System.out.println(intList);
    }
}

HashSet’s add() method adds the components to the set. It’s important to note that the elements are distinct. Because the sets are unordered, there is no way to acquire the components in the order they were inserted.

Java Conversion of a Set to a List

Let’s make a list out of the set. There are several options for doing so. In fact, each method is distinct from the others. However, the distinctions are minor.

Constructor of a List with a Set argument

The simplest way to convert a set to a list is to use the set as an argument when building the list. The constructor is invoked due to this, and the constructor takes care of the rest. In Java, collections feature a constructor where the direct set is provided to produce a List.

Algorithm:

  • Obtain the set you intend to transform.
  • By supplying the set as an argument to the constructor, you can make a list.
  • Return the created List.
import java.util.*;
 
public class Main {
 
    public static void main(String[] args)
    {
        Set<Integer> intList = new HashSet<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        intList.add(1);
 
     List<Integer> arr = new ArrayList<>(intList);
     System.out.println(arr);
     System.out.println(arr.get(1));
 
    }
}

The elements are now arranged because the set has been changed to a list. That means we can retrieve details by index using the get() method.

Example: Program for converting a Set to List in Java
import java.util.*;
import java.util.stream.*;

class Codeunderscored {

	// 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> laptopHashSet = new HashSet<String>();

		// Add elements to set
		laptopHashSet.add("Geeks");
		laptopHashSet.add("For");
		laptopHashSet.add("Geeks");
		laptopHashSet.add("Example");
		laptopHashSet.add("Set");

		// Print the Set
		System.out.println("Set: " + laptopHashSet);

		// construct a new List from Set
		List<String> list = convertSetToList(laptopHashSet);

		// Print the List
		System.out.println("List: " + list);
	}
}
Example: Using a Constructor
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> codeSet = new HashSet<String>();
  
        // Add elements to set
        codeSet.add("Code");
        codeSet.add("Underscored");
        codeSet.add("Set");
        codeSet.add("to");
        codeSet.add("list");
        codeSet.add("example");
  
        // Print the Set
        System.out.println("Set: " + codeSet);
  
        // construct a new List from Set
        List<String> list = convertSetToList(hash_Set);
  
        // Print the List
        System.out.println("List: " + list);
    }
}

Using a traditional loop

To explicitly copy the elements from the set to the list, we may use the good old for a loop. The brute force or naive method is making an empty list and then adding each element of the set to it.

Algorithm:

  • Obtain the set that will be transformed.
  • Make an empty list.
  • Fill in the list with each element from the set.
  • Return the resultant List created.
import java.util.*;
 
public class Main {
 
    public static void main(String[] args)
    {
        Set<Integer> intList = new HashSet<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        intList.add(1);
 
     List<Integer> arr = new ArrayList<>(intList);
        for (int i : a)
            arr.add(i);
        System.out.println(arr);
        System.out.println(arr.get(1));
    }   
}

The for loop iterates across the set, adding each element to the list.

Example: Program for converting a Set to List in Java 8
import java.util.*;
import java.util.stream.*;

class Codeunderscored {

	// 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("Code");
		hash_Set.add("For");
		hash_Set.add("Underscored");
		hash_Set.add("Python");
		hash_Set.add("Set");

		// 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);
	}
}
Example 3: Using a traditional loop
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> codeSet = new HashSet<String>();
  
        // Add elements to set
        codeSet.add("Code");
        codeSet.add("Underscored");
        codeSet.add("Set");
        codeSet.add("to");
        codeSet.add("list");
        codeSet.add("example");
  
        // Print the Set
        System.out.println("Set: " + codeSet);
  
        // construct a new List from Set
        List<String> list = convertSetToList(codeSet);
  
        // Print the List
        System.out.println("List: " + list);
    }
}

Use the addAll() function to add all items to a list.

AddAll() is a list method that adds multiple values to the list at once. This operation may be familiar to you from its use in merging two lists. addAll() can also add a set’s elements to a list.

import java.util.*;
 
public class Main {
 
    public static void main(String[] args)
    {
        Set<Integer> intList = new HashSet<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        intList.add(1);
 
     List<Integer> arr = new ArrayList<>();
        arr.addAll(intList);
        System.out.println(arr);
        System.out.println(arr.get(1));
    }
}

}

The collect() method of the Stream API

From Java 8, Stream.collect() is supported. All Stream elements are collected into a List object via the ToList collector. In Java 8, you can convert a set to a list by using Set.stream() to convert the set to a sequential Stream, then using a Collector to gather the input elements into a new List.

// This is Generic method to convert a set to a list
public static <T> List<T> convertToList(Set<T> set) {
    return set.stream().collect(Collectors.toList());
}

We can use Collectors.toCollection() to specify the desired Collection because Collectors.toList() does not guarantee the type of the List returned:

// This a Generic method to convert a set to `ArrayList`
public static <T> List<T> convertToList(T[] arr) {
    return set.stream().collect(Collectors.toCollection(ArrayList::new));
}

Algorithm:

  • Obtain the HashMap that will be transformed.
  • Make a stream out of the Set
  • Convert the set to a list and add it to your collection.
  • Return the List that was collected.
import java.util.*;
import java.util.stream.Collectors;
 
 
public class Main {
 
    public static void main(String[] args)
    {
        Set<Integer> intList = new HashSet<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        intList.add(1);
 
     List<Integer> arr;
 
        arr = intList.stream().collect(Collectors.toList());
        System.out.println(arr);
        System.out.println(arr.get(1));
    }
}

The type, mutability, serializability, and thread safety of the List returned are not guaranteed. That is according to the documentation for stream.collect(). Use toCollection(Supplier) if you need greater control over the returned List.

Use toCollection(ArrayList::new) to specify the list type

pubimport java.util.*;
import java.util.stream.Collectors;
 
 
public class Main {
 
    public static void main(String[] args)
    {
        Set<Integer> intList = new HashSet<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        intList.add(1);
 
     List<Integer> arr;
 
  arr = intList.stream().collect(Collectors.toCollection(ArrayList::new));
        System.out.println(arr);
        System.out.println(arr.get(1));
    }
}

Example: Program for converting a HashMap to TreeMap in Java

import java.util.*;
import java.util.stream.*;

class Codeunderscored {

	// Generic function to convert set to list
	public static <T> List<T> convertSetToList(Set<T> set)
	{
		// create a list from Set
		return set

			// Create stream from the Set
			.stream()

			// Convert the set to list and collect it
			.collect(Collectors.toList());
	}

	public static void main(String args[])
	{

		// Create a Set using HashSet
		Set<String> languageSet = new HashSet<String>();

		// Add elements to set
		languageSet.add("Java");
		languageSet.add("Python");
		languageSet.add("HTML");
		languageSet.add("JavaScript");
		languageSet.add("Kotlin");

		// Print the Set
		System.out.println("Set: " + languageSet);

		// construct a new List from Set
		List<String> list = convertSetToList(languageSet);

		// Print the List
		System.out.println("List: " + list);
	}
}

Using the List.copyOf() function

The copyOf() method is available in Java 10 and later. The method returns an immutable List containing the elements of the supplied Collection in the order in which they were iterated. There can’t be any null elements in the list. If the set includes ‘ null, ‘the method throws a null pointer exception.

import java.util.*;
import java.util.stream.Collectors;
 
 
public class Main {
 
    public static void main(String[] args)
    {
        Set<Integer> intList = new HashSet<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        intList.add(1);
 
     List<Integer> arr;
 
        arr = List.copyOf(intList);
        System.out.println(arr);
        System.out.println(arr.get(1));
    }
}

Attempting to convert a set to a list after adding a null:

import java.util.*;
import java.util.stream.Collectors;
 
public class Main {
 
    public static void main(String[] args)
    {
        Set<Integer> intList  = new HashSet<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        intList.add(1);
        intList.add(null);
 
     List<Integer> arr;
 
        arr = List.copyOf(intList);
        System.out.println(arr);
        System.out.println(arr.get(1));
    }
}

If you try to add a new element to an immutable list, you’ll get an error similar to this. To convert a set with a null element to a list, use the addAll() method:

import java.util.*;
import java.util.stream.Collectors;
 
 
public class Main {
 
    public static void main(String[] args)
    {
        Set<Integer> intList = new HashSet<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        intList.add(1);
        intList.add(null);
 
     List<Integer> arr = new ArrayList<>();
     arr.addAll(intList);
 
      //  arr = List.copyOf(intList);
        System.out.println(intList);
        System.out.println(arr.get(1));
    }
}

It’s worth noting that the null is at the top of the list.

Example: Using the List.copyOf() function

public void usingJava10ToConvertSetToList() {
    Set<Integer> positionSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
    List<Integer> targetList = List.copyOf(positionSet);
}

Using Guava Library List.newArrayList(set)

Lists.newArrayList(set) generates a mutable ArrayList instance using the supplied set’s elements. If we need to add or remove elements later, or if some of the components are null, this is better.

// This is a Generic method to convert a set to a list
public static <T> List<T> convertToList(Set<T> set) {
    return Lists.newArrayList(set);
}

ImmutableList.copyOf is another option that returns an immutable list containing the set of elements supplied. When mutability isn’t required, you should use this.

// This is a Generic method to convert a set to a list
public static <T> List<T> convertToList(Set<T> set) {
    return ImmutableList.copyOf(set);
}

Algorithm:

  • Obtain the Set that will be transformed.
  • Using Lists, create a new List.
  • You can create an array list by supplying the set as an argument to the Guava library’s newArrayList() function.
  • Return the List that was created.
Example: Program for converting HashMap to TreeMap in Java
import java.util.*;
import java.util.stream.*;

class Codeunderscored {

	// Generic function to convert set to list
	public static <T> List<T> convertSetToList(Set<T> set)
	{
		// create a list from Set
		return Lists.newArrayList(set);
	}

	public static void main(String args[])
	{

		// Create a Set using HashSet
		Set<String> languageSet = new HashSet<String>();

		// Add elements to set
		languageSet.add("Java");
		languageSet.add("Python");
		languageSet.add("HTML");
		languageSet.add("JavaScript");
		languageSet.add("Kotlin");

		// Print the Set
		System.out.println("Set: " + languageSet);

		// construct a new List from Set
		List<String> list = convertSetToList(languageSet);

		// Print the List
		System.out.println("List: " + list);
	}
}
Example: Conversion using Guava

public void usingGuavaToConvertSetToList() {

    Set<Integer> positionList = Sets.newHashSet(0, 1, 2, 3, 4, 5);
    List<Integer> targetList = Lists.newArrayList(positionList);
}

It is pretty similar to the java technique but with less code duplication.

Using the Apache Commons Collections

Then, to convert between a List and a Set, we’ll utilize the Commons Collections API:

public void usingCommonsCollectionsToConvertSetToList() {

Set<Integer> positionSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = new ArrayList<>(6);
CollectionUtils.addAll(targetList, positionSet);

}

Conclusion

The java.util.Collection interface is extended by a Java set, which is part of java.util package. There can be no duplicate items in a Java set, and only one null element is allowed. Further, a Java list is a collection of things arranged in a specific order. In fact, a Java list, unlike a Java Set, can have duplicate values.

We saw some highly creative approaches to converting a set to a list. It’s crucial to pay attention to each technique’s type of list. The copyOf() method, for example, creates an immutable list that cannot include null elements. Stream.collect(), on the other hand, makes no guarantees. Nevertheless, the constructor and addAll() functions are the most reliable of the batch.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *