Iterate Over Unmodifiable Collection in Java


Being a programmer we must have developed an application that performs CRUD operations. Here, the term CRUD means Create, Read, Update and delete. The collection on which these operations can be performed is called as modifiable collection. However, there is a way to make a collection unmodifiable so that one cannot make any changes to the original collection. Although we can't alter the elements, we can iterate over this collection. To iterate over unmodifiable collections in Java, we can use either the for-each loop or iterator(). Let's discuss it in detail.

Iterate Over Unmodifiable Collection in Java

As mentioned earlier, a collection is considered unmodifiable if we can't modify its elements by any means. But, by default all the collection classes are modifiable. Don't worry, Java provides a way to make a collection unmodifiable and to do so we can use the Collections.unmodifiableCollection() method that accepts a modifiable collection as a parameter and returns an unmodifiable view.

Syntax

Collection<Type>instance=Collections.unmodifiableCollection(collection_name);

Here,

Type specifies the type of unmodifiable collection but it must match the original modifiable collection.

collection_name specifies the instance of modifiable collection.

instance depicts the reference of new unmodifiable collection.

The one benefit of using an unmodifiable collection is that it is more memory efficient than the modifiable collection as it does not require maintaining the details of the modifications. If we attempt to make any changes directly or using iterator(), we will encounter java.lang.UnsupportedOperationException.

Example 1

The following example illustrates what would happen if we try to add a new element to the unmodifiable ArrayList collection. We will first create an instance of ArrayList class and store a few elements in it using the built-in method 'add()'. After making this collection unmodifiable, we will add a new element that will throw an error.

import java.util.*;
public class ArrayObj {
   public static void main(String[] args) {
      // Creating arraylist 
      ArrayList<Integer> araylist = new ArrayList<>();
      // Adding elements in arraylist
      araylist.add(1);
      araylist.add(2);
      araylist.add(1);
      araylist.add(0);
      araylist.add(9);
      araylist.add(6);
      // making arraylist unmodifiable
      Collection<Integer> newArrayLst
         = Collections.unmodifiableCollection(araylist);
      // trying to add a new elements
      newArrayLst.add(5); // this line will throw error 
      System.out.println("Elements of the list : ");
      // loop to iterate through elements
      for (Integer print : newArrayLst) {
         // printing the elements
         System.out.println(print);
      }
   }
}

Output

Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1067)
at ArrayObj.main(ArrayObj.java:17)

Example 2

In the following example, we will iterate through the elements of unmodifiable ArrayList collection using for-each loop.

import java.util.*;
public class ArrayObj {
   public static void main(String[] args) {
      // Creating arraylist 
      ArrayList<Integer> araylist = new ArrayList<>();
      // Adding elements in arraylist
      araylist.add(1);
      araylist.add(2);
      araylist.add(1);
      araylist.add(0);
      araylist.add(9);
      araylist.add(6);
      // making arraylist unmodifiable
      Collection<Integer> newArrayLst
         = Collections.unmodifiableCollection(araylist);
      System.out.println("Elements of the list : ");
      // loop to iterate through elements
      for (Integer print : newArrayLst) {
         // printing the elements
         System.out.println(print);
      }
   }
}

Output

Elements of the list : 
1
2
1
0
9
6

Example 3

In this example, we will show how one can iterate over an unmodifiable TreeSet collection using for-each loop.

import java.util.*;
public class TreeStExample {
   public static void main(String args[]) {
      // Creating tree set
      TreeSet<String> treeSt = new TreeSet<>();
      // Adding elements in tree set
      treeSt.add("Tutorix");
      treeSt.add("Simply");
      treeSt.add("Easy");
      treeSt.add("Learning");
      treeSt.add("Tutorials");
      treeSt.add("Point");
      // making TreeSet unmodifiable
      Collection<String> newTreeSt
         = Collections.unmodifiableCollection(treeSt);
      System.out.println("Elements in the TreeSet: ");
      // iterating over unmodifiable TreeSet 
      for (String print :  treeSt) {
         // printing the elements
         System.out.println(print);
      }
   }
}

Output

Elements in the TreeSet: 
Easy
Learning
Point
Simply
Tutorials
Tutorix

Conclusion

In this article, we have learned about modifiable and unmodifiable collections and how one can change a modifiable collection into an unmodifiable one using the Collections.unmodifiableCollection() method. Compared to a modifiable collection, the unmodifiable collection is more memory efficient. Also, we discovered how to iterate through the elements of unmodifiable collections using a for-each loop.

Updated on: 17-Aug-2023

135 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements