Converting Collection to unmodifiable Set

In this post under Java, I will show with example how to convert a collection to unmodifiable set.

To convert a collection to an immutable Set, we take help of “Set” interface static method “copyOf”.

Below is the complete code for your reference.

Main class

1  package core.collection;
2  
3  import java.util.ArrayList;
4  import java.util.List;
5  import java.util.Set;
6  
7  public class CollectionToSetConversionDemo {
8      public static void main(String[] args) {
9          List<Integer> integerList = new ArrayList<>(0);
10         integerList.add(1);
11         integerList.add(2);
12         integerList.add(3);
13         integerList.add(4);
14         integerList.add(5);
15 
16         Set<Integer> integerSet = Set.copyOf(integerList);
17         System.out.println(integerSet);
18     }
19 }

In the above code, at line 9 I create a list of type parameter “Integer” named “integerList”.

From line 10 to 14, I populate the list.

At line 16, I call the “Set” interface static method “copyOf” and pass the list as an argument. The return value is a immutable set.

At line 17, I print the elements of the set.

In this way, we can convert a collection to immutable set.

Leave a comment