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




Java - Sort List Elements


As we have seen the implementations of a List are :

  1. ArrayList

  2. LinkedList


Let us see the ArrayList implementation,


How to sort a List in Ascending Order?


The Collections.sort() Method is used to sort a List in Ascending order.


Example :



import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MyApplication {
    public static void main(String[] args) {

        List x = new ArrayList<>();

        x.add("Mohan");
        x.add("Kriti");
        x.add("Salim");

        Collections.sort(x);

        for (String data : x) {
            System.out.println(data);
        }
    }
}


Output :



  Kriti
  Mohan
  Salim

So, in the above code we have created a List,


List x = new ArrayList<>();

And initialised three names to the variable x,


x.add("Mohan");
x.add("Kriti");
x.add("Salim");

Below is how the values are positioned in the List,

Spring_Boot

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


Collections.sort(x);

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

Spring_Boot

And we get the below output.

Output :



  Kriti
  Mohan
  Salim

How to sort a List with numbers in Increasing Order?


Even here the Collections.sort() Method is used to sort a List with numbers in Increasing Order.


Example :



import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MyApplication {
    public static void main(String[] args) {

        List x = new ArrayList<>();

        x.add(5);
        x.add(3);
        x.add(2);
        x.add(4);

        Collections.sort(x);

        for (Integer data : x) {
            System.out.println(data);
        }
    }
}


Output :



  2
  3
  4
  5

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


List x = new ArrayList<>();

x.add(5);
x.add(3);
x.add(2);
x.add(4);

Below is how the values are positioned in the List,

Spring_Boot

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


Collections.sort(x);

And the numbers in the List x gets sorted.

Spring_Boot

And we get the below output.

Output :



  2
  3
  4
  5

Note : The same code applies for LinkedList as well. Just that you need to replace ArrayList LinkedList.