How to convert set to List in Java

Read Time:5 Minute, 51 Second

Table of Contents

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.

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.

SUGGESTED READ

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.

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
Example: Using a Constructor

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.

SUGGESTED READ

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.

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

Example: Program for converting a Set to List in Java 8
Example 3: Using a traditional loop

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.

}

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.

SUGGESTED READ

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

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.

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

SUGGESTED READ

Example: Program for converting a HashMap to TreeMap in Java

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.

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

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:

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

SUGGESTED READ

Example: Using the List.copyOf() function

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.

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.

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
Example: Conversion using Guava

SUGGESTED READ

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:

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.

Source: https://www.codeunderscored.com/how-to-convert-set-to-list-in-java/

WP Ad Inserter plugin for WordPress