Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   RUBY   
   C++   




SORTED() - FUNCTION


The sorted() Function is used to sort a Set in Ascending order and in addition it doesn't change the contents of the actual Set.


Example :



fun main() {
    var x = mutableSetOf("Mohan", "Kriti", "Salim")
    var y = x.sorted()
    println("The contents of the Set x is unchanged : "+x)
    println("The sorted Set assigned to Set y : "+y)
}


Output :



  The contents of the Set x is unchanged : [Mohan, Kriti, Salim]
  The sorted Set assigned to Set y : [Kriti, Mohan, Salim]

So, in the above code we have created a Set and initialised to the variable x.


val x = mutableSetOf("Mohan", "Kriti", "Salim")

Below is how the values are positioned in the Set,

java_Collections

Then we have used the sorted() method to sort the Set x in ascending order.


var y = x.sorted()

And initialised the sorted Set to a new Set y.


Now, if you look at the output of y. You can see that the Set y has the sorted values with Kriti as the first value, Mohan second and Salim as the third.

java_Collections

And when you look at the value of x,

java_Collections

The values of the set x is unchanged.