Converting Between a List and a Set in Java

1. Overview

In this quick tutorial, we’ll take a look at the conversion between a List and a Set, starting with Plain Java, using Guava and the Apache Commons Collections library, and finally with Java 10.

2. Convert List to Set

2.1. With Plain Java

Let’s start with converting a List to a Set using Java:

public void givenUsingCoreJava_whenListConvertedToSet_thenCorrect() {
    List<Integer> sourceList = Arrays.asList(0, 1, 2, 3, 4, 5);
    Set<Integer> targetSet = new HashSet<>(sourceList);
}

As we can see, the conversion process is type-safe and straightforward, since the constructors of each collection do accept another collection as a source.

2.2. With Guava

Let’s do the same conversion using Guava:

public void givenUsingGuava_whenListConvertedToSet_thenCorrect() {
    List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
    Set<Integer> targetSet = Sets.newHashSet(sourceList);
}

2.3. With Apache Commons Collections

Next let’s use the Commons Collections API to convert between a List and a Set:

public void givenUsingCommonsCollections_whenListConvertedToSet_thenCorrect() {
    List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
    Set<Integer> targetSet = new HashSet<>(6);
    CollectionUtils.addAll(targetSet, sourceList);
}

2.4. With Java 10

One additional option is to use the Set.copyOf static factory method introduced in Java 10:

public void givenUsingJava10_whenListConvertedToSet_thenCorrect() {
    List sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
    Set targetSet = Set.copyOf(sourceList);
}

Note that a Set created this way is unmodifiable.

3. Convert Set to List

3.1. With Plain Java

Now let’s do the reverse conversion, from a Set to a List, using Java:

public void givenUsingCoreJava_whenSetConvertedToList_thenCorrect() {
   Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
   List<Integer> targetList = new ArrayList<>(sourceSet);
}

3.2. With Guava

We can do the same using the Guava solution:

public void givenUsingGuava_whenSetConvertedToList_thenCorrect() {
    Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
    List<Integer> targetList = Lists.newArrayList(sourceSet);
}

This is very similar to the java approach, only with a little less duplicated code.

3.3. With Apache Commons Collections

Now let’s see the Commons Collections solution to convert between a Set and a List:

public void givenUsingCommonsCollections_whenSetConvertedToList_thenCorrect() {
    Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
    List<Integer> targetList = new ArrayList<>(6);
    CollectionUtils.addAll(targetList, sourceSet);
}

3.4. With Java 10

Finally, we can use the List.copyOf that’s been introduced in Java 10:

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

We need to keep in mind that the resulting List is unmodifiable.

4. Conclusion

The implementation of all of these examples and code snippets can be found over on GitHub. This is a Maven-based project, so it should be easy to import and run as it is.

Related posts:

Java Program to Implement the Checksum Method for Small String Messages and Detect
Java Program to Check whether Undirected Graph is Connected using DFS
JavaScript Map and Set
Giới thiệu Java Service Provider Interface (SPI) – Tạo các ứng dụng Java dễ mở rộng
Java Program to Find All Pairs Shortest Path
Lớp Collectors trong Java 8
Java Concurrency Interview Questions and Answers
SOAP Web service: Authentication trong JAX-WS
Spring 5 and Servlet 4 – The PushBuilder
Java Program to implement Associate Array
Java Program to Find the Connected Components of an UnDirected Graph
Java Program to Find Minimum Element in an Array using Linear Search
Java Program to Check if an UnDirected Graph is a Tree or Not Using DFS
OAuth2.0 and Dynamic Client Registration
Python Set pop()
Java Program to Implement HashSet API
Find the Registered Spring Security Filters
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Java Program to Implement Hamiltonian Cycle Algorithm
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach
A Guide to Java HashMap
Java Program to Implement Hash Tables with Linear Probing
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
Java Program to Construct K-D Tree for 2 Dimensional Data
Spring Webflux with Kotlin
Template Engines for Spring
Java String to InputStream
Java Program to Implement Find all Back Edges in a Graph
Java Program to Implement the String Search Algorithm for Short Text Sizes
Spring MVC and the @ModelAttribute Annotation
Serialization và Deserialization trong java
CharSequence vs. String in Java