Friday, February 13, 2026
HomeLanguagesJavaJava Collections unmodifiableSortedSet​() Method with Examples

Java Collections unmodifiableSortedSet​() Method with Examples

The unmodifiableSortedSet() method of Java Collections is available in TreeSet. A Tree Set is a data structure that can store elements in order.

Syntax:

SortedSet<datatype> data = new TreeSet<String>();  

where,

  • datatype specifies the type of elements
  • data is the input data.

 unmodifiableSortedSet() Method 

The unmodifiableSortedSet() method of the Java Collections class is used to get an unmodifiable view of the specified sorted set.

Syntax:

public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> data)   

where data is the sorted set that is returned in an unmodifiable view.

Return type: This method returns an unmodifiable view of the specified Sorted Set.

Example 1:

Demonstration before and after modification

Java




import java.util.*;
  
public class GFG1 {
    // main method
    public static void main(String[] args)
    {
        // create a set named data
        SortedSet<String> data = new TreeSet<String>();
        
        // Add values in the data
        data.add("java");
        data.add("Python");
        data.add("R");
        data.add("sql");
        
        // Create a Unmodifiable sorted set
        SortedSet<String> data2
            = Collections.unmodifiableSortedSet(data);
        
        // display
        System.out.println(data);
        
        // add to data
        data.add("bigdata/iot");
        
        // display
        System.out.println(data2);
    }
}


Output

[Python, R, java, sql]
[Python, R, bigdata/iot, java, sql]

Example 2:

Java




import java.util.*;
  
public class GFG1 {
    // main method
    public static void main(String[] args)
    {
        // create a set named data
        SortedSet<Integer> data = new TreeSet<Integer>();
        
        // Add values in the data
        data.add(1);
        data.add(2);
        data.add(3);
        data.add(34);
        
        // Create a Unmodifiable sorted set
        SortedSet<Integer> data2
            = Collections.unmodifiableSortedSet(data);
        
        // display
        System.out.println(data);
        
        // add to data
        data.add(32);
        
        // display
        System.out.println(data2);
    }
}


Output

[1, 2, 3, 34]
[1, 2, 3, 32, 34]
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32502 POSTS0 COMMENTS
Milvus
128 POSTS0 COMMENTS
Nango Kala
6880 POSTS0 COMMENTS
Nicole Veronica
12002 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12093 POSTS0 COMMENTS
Shaida Kate Naidoo
7011 POSTS0 COMMENTS
Ted Musemwa
7253 POSTS0 COMMENTS
Thapelo Manthata
6963 POSTS0 COMMENTS
Umr Jansen
6953 POSTS0 COMMENTS