This post will discuss how to add the contents of a List into a Set in Java.

1. Using Set.addAll() method

The standard solution to add all elements of the specified collection to the set is using the addAll() method, as shown below:

Download  Run Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

 
Since a Set doesn’t permit duplicates, any common elements will be silently discarded.

Download  Run Code

Output:

[1, 2, 3, 4, 5, 7]

 
Note that the behavior of the addAll() method is undefined if the list is modified while the operation is in progress. Also, any mutable object present in the list is modified after calling the addAll() method, the changes are reflected in the set as well. This is because both list and set hold the same references of the objects inside them.

This behavior is demonstrated below. To handle this, pass a copy of each object to the Set.add() method, as discussed below.[3]

Download  Run Code

Output:

[{1, 2}, {3, 4}, {5, 7}, {1, 3}]
[{2, 2}, {3, 4}, {5, 7}, {1, 3}]

2. Using Apache Commons Collections

You can also use CollectionUtils.addAll() from by Apache Commons Collections that works similar to the Collections.addAll().

Download Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

3. Using Set.add() method

With Java 8, you can use Stream API to call the add() method on the set for each list item.

Download  Run Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

 
This approach faces the same issue as the addAll() method, i.e., both list and set hold the same references of the objects inside them. This can be easily handled by inserting a copy of each object into the set, instead of inserting the actual object itself.

Download  Run Code

Output:

[{1, 2}, {3, 4}, {5, 7}, {1, 3}]
[{1, 2}, {3, 4}, {5, 7}, {1, 3}]

That’s all about adding the contents of a List into a Set in Java.