Pages

Friday, July 20, 2018

How To Sort ArrayList In Java – Collections.Sort() Examples

How To Sort ArrayList In Java :

In this post, we will learn how to sort ArrayList in java. This is very easy to understand and remember the methods.


1) Sorting ArrayList in ascending order
2) Sorting ArrayList in descending order



How To Sort ArrayList In Java – Collections.Sort



Sorting List in Ascending order:
package com.java.w3schools;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FruitsArrayList {
      public static void main(String[] args) {
            List<String> fruits = new ArrayList<>();
            fruits.add("Mango");
            fruits.add("Orange");
            fruits.add("Apple");
            fruits.add("Banana");
            System.out.println("Printing fruits before sorting : " + fruits);
            Collections.sort(fruits);
            System.out.println("Printing fruits after sorting : " + fruits);
      }
}


Output:

Printing fruits before sorting : [Mango, Orange, Apple, Banana]
Printing fruits after sorting : [Apple, Banana, Mango, Orange]
Collections class has a method sort() which takes List as argument. This method does sorting in ascending order. Observer the output of the above program.

Sorting List in Descending order:

Just replace the Collection.sort with the following code snippet.
Collections.sort(fruits, Collections.reverseOrder());

Output:

Printing fruits before sorting : [Mango, Orange, Apple, Banana]
Printing fruits after sorting : [Orange, Mango, Banana, Apple]
Collections class has a method for sorting the list elements in reverse order that is descending order.
In the next post, we will learn how to sort a list of students where Student is a user defined class with properties of id, name, age.

No comments:

Post a Comment

Please do not add any spam links in the comments section.