Converting a collection to immutable collection

In this post under Java Collections, I will show with example how to create immutable collections.

Below is the complete code for your reference.

Main class

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

In the above code, at line 10, I create a list of type argument “Integer” class and populate it.

At line 17, I create an immutable collection by calling static “unmodifiableCollection” method available on “Collections” class and passing the collection as an argument.

In this case it is an integer list.

In this way we can create an immutable collection.

Please note any modification to source collection after obtaining the immutable collection, the immutable collection will also get affected.

Leave a comment