How to Sort Integer ArrayList in Java – Ascending and Descending order

We have seen arraylist  is an Unordered and without sorted one by its default implementation. In this post we will see How to Sort ArrayList in Java. To Sort arraylist we have method called sort in Collections class. By default this method will sort in ascending order.

How to Sort ArrayList in Java

How to Sort ArrayList in Java

How to sort Arraylist in Java – in Reverse Direction

How to Sort ArrayList in Java

How to Sort ArrayList in Java

 

Now we will see the example of How to Sort ArrayList in Java which hold Integer Values.


package ArrayList;

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

public class ArrayListSortInteger {

public static void main(String[] args) {
 List<Integer> integersList = new ArrayList<>();
 integersList.add(1);
 integersList.add(45);
 integersList.add(3);

 System.out.println("Integer List Without Sort " +integersList);//1,45,3

 // Collections.sort() --> sort the list in ascending order
 Collections.sort(integersList);

 System.out.println("Integer List With Sort " +integersList);//1,3,45

 //// Collections.sort() --> sort the list in descending (reverse) order
 Collections.sort(integersList, Collections.reverseOrder());

 System.out.println("Integer List With Sort in Reverse Order "+integersList);//45,3,1
 }
}

Output will be like this:


Integer List Without Sort [1, 45, 3]
Integer List With Sort [1, 3, 45]
Integer List With Sort in Reverse Order [45, 3, 1]

We have seen sorting of Integer arraylist in ascending and descending order. But How string will be sorted in list. Also How String with Uppercase and with lowercase will be sorted in list? Also How String will be sorted in reverse order.? Also How user defined class will be sorted? We will get answers to all these questions in our next tutorial.

If you have any questions on this tutorial, please post your questions in the comment box. Also If you like this tutorial please share it with your friends. Also To get regular updates from learnfromexample please subscribe to our website.

Related Tutorial Link Which You might Like:

  1. How to Convert ArrayList to Array in Java
  2. How to find the count of an ArrayList
  3. How to sort User Defined Objects in Arraylist

 

 

Leave a comment

Your email address will not be published. Required fields are marked *