In this post under Java, I will show with example how to convert a collection to unmodifiable list.
To convert a collection to an immutable List, we take help of “List” interface static method “copyOf”.
Below is the complete code for your reference.
Main class
1 package core.collection;
2
3 import java.util.HashSet;
4 import java.util.List;
5 import java.util.Set;
6
7 public class CollectionToListConversionDemo {
8 public static void main(String[] args) {
9 Set<Integer> integerSet = new HashSet<>(0);
10 integerSet.add(1);
11 integerSet.add(2);
12 integerSet.add(3);
13 integerSet.add(4);
14 integerSet.add(5);
15
16 List<Integer> integerList = List.copyOf(integerSet);
17 System.out.println(integerList);
18 }
19 }
In the above code, at line 9 I create a set of type parameter “Integer” named “integerSet”.
From line 10 to 14, I populate the set.
At line 16, I call the “List” interface static method “copyOf” and pass the set as an argument. The return value is a immutable list.
At line 17, I print the elements of the list.
In this way, we can convert a collection to immutable list.