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




LIST - sort()


The 'sort()' Function is used to sort a List in Ascending order.


Using sort() method to sort List of Strings in Ascending order


Example :



fun main() {
    val x = mutableListOf("Mohan", "Kriti", "Salim")
    x.sort()
    println("The Sorted List in ascending order is "+x)
}


Output :



 The Sorted List in ascending order is [Kriti, Mohan, Salim]

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


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

Below is how the values are positioned in the List,


java_Collections

Then we have used the 'sort()' method to sort the List 'x' in ascending order.


x.sort()

And the List 'x' gets sorted with 'Kriti' as the first value, 'Mohan' second and 'Salim' as the third.


java_Collections

And we get the below output.


The Sorted List in ascending order is [Kriti, Mohan, Salim]

Using sort() method to sort a List of numbers in increasing order


Example :



fun main() {
    val x = mutableListOf(5, 3, 2, 4)
    x.sort()
    println("The Sorted List in increasing order is "+x)
}


Output :



 The Sorted List in increasing order is [2, 3, 4, 5]

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


val x = mutableListOf(5, 3, 2, 4)

Below is how the values are positioned in the List,


java_Collections

Then we have used the 'sort()' method to sort the List 'x' in increasing order.


x.sort()

And the numbers in the List 'x' gets sorted.


java_Collections

And we get the below output.


The Sorted List in increasing order is [2, 3, 4, 5]