BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl
Home / java / How to sort ArrayList in Java

How to sort ArrayList in Java

By Chaitanya Singh

In this tutorial, you will learn how to sort ArrayList in Java. We will see java programs in this guide, to sort an ArrayList in ascending and descending order.

What is an ArrayList?

Arraylist is a class in java that implements List interface. It is based on an Array data structure. It is widely used because of the functionality and flexibility it offers. Most of the developers choose Arraylist over Array as ArrayList can dynamically grow and shrink after addition and removal of elements.

This is how an ArrayList looks like:

[Shyam, Chaitanya, Steve, Ram]

After sorting this ArrayList in ascending order:

[Chaitanya, Ram, Shyam, Steve]

After sorting the original ArrayList in descending order:

[Steve, Shyam, Ram, Chaitanya]

Example 1: Sorting ArrayList in Ascending order

In this example, we have an ArrayList of String type. We are sorting the given ArrayList in ascending order using Collections.sort() method. Since this ArrayList is of string type, the elements are sorted in ascending alphabetical order.

import java.util.*;
public class JavaExample {
  public static void main(String args[]){
    ArrayList<String> listOfCountries = new ArrayList<>();
    listOfCountries.add("India");
    listOfCountries.add("US");
    listOfCountries.add("China");
    listOfCountries.add("Denmark");

    // Original unsorted list
    System.out.println("Before Sorting: "+ listOfCountries);

    //Sorting the ArrayList using sort() method
    Collections.sort(listOfCountries);

    // Printing sorted ArrayList
    System.out.println("After Sorting: "+ listOfCountries);
  }
}

Output:
Sort ArrayList in Java

Example 2: Sorting ArrayList of Integer Type

In this example, we have an ArrayList of integers and we are sorting it using the sort() method. This program is similar to the above program except that the list is of integer type here so the ArrayList elements are integers.

import java.util.*;
public class JavaExample{

  public static void main(String args[]){
    ArrayList<Integer> arraylist = new ArrayList<>();
    arraylist.add(11);
    arraylist.add(2);
    arraylist.add(7);
    arraylist.add(3);

    //Before sorting
    System.out.println("Before Sorting: "+ arraylist);

    // Sorting the list of integers using sort() method
    Collections.sort(arraylist);

    //After sorting
    System.out.println("After Sorting: "+ arraylist);
  }
}

Output:

Before Sorting: [11, 2, 7, 3]
After Sorting: [2, 3, 7, 11]

Example 3: Sorting an ArrayList in Descending order

In this program, we are sorting the given ArrayList in descending order. To sort an ArrayList in descending order, we just have to pass the Collection.reverseOrder() as a second parameter in the Collections.sort() method as shown below. Similarly, we can sort an ArrayList of integer type in descending order as well.

import java.util.*;
public class JavaExample{

  public static void main(String args[]){
    ArrayList<String> arraylist = new ArrayList<>();
    arraylist.add("Apple");
    arraylist.add("Orange");
    arraylist.add("Kiwi");
    arraylist.add("Banana");
    arraylist.add("Mango");

    //Before sorting
    System.out.println("Before Sorting: "+ arraylist);

    // Sorting the list in descending order
    Collections.sort(arraylist, Collections.reverseOrder());

    //After sorting
    System.out.println("After Sorting: "+ arraylist);
  }
}

Output:
Sorting an ArrayList in Descending order

Example 4: Sort ArrayList entered by user in descending order

In this example, user is asked to enter the size of ArrayList. This is read and stored in an int variable size. A while loop runs to read and add the user entered elements to the ArrayList. Once the list is populated with the user entered elements, the list is sorted in reverse order by using the sort() method similar to the Example 3.

import java.util.*;
public class JavaExample {
  public static void main(String[] args) {
    int i=0, size;
    Scanner scan = new Scanner(System.in);
    ArrayList<String> list = new ArrayList<>();

    System.out.println("How many elements you want in list? ");
    size = scan.nextInt();
    Scanner scan2 = new Scanner(System.in);
    System.out.println("Enter elements: ");
    while(i<size)
    {
      list.add(scan2.nextLine());
      i++;
    }

    //Before sorting
    System.out.println("Before Sorting: "+ list);

    // Sorting the list in descending order
    Collections.sort(list, Collections.reverseOrder());

    //After sorting
    System.out.println("After Sorting: "+ list);
  }
}

Output:
Sort ArrayList Descending order user input
Related guides:

  1. Sort ArrayList in descending order
  2. Sort ArrayList of Objects using Comparable and Comparator
❮ Java ArrayListJava Collections ❯

Posted Under: java | Tags: Collections, Java-ArrayList

Comments

  1. papajo says

    December 17, 2014 at 5:53 PM

    Hi, good article, but will Collections.sort eliminate duplicates in case the list contains any duplicates? If not can you show how to eliminate the duplicates?

    Reply
    • Chaitanya Singh says

      December 19, 2014 at 5:09 AM

      Refer this: https://beginnersbook.com/2014/10/how-to-remove-repeated-elements-from-arraylist/

      Reply
  2. Frank says

    July 6, 2015 at 3:22 PM

    For the main method it is supposed to be (String[] args) not (String args[])

    Reply
    • Chaitanya Singh says

      July 10, 2015 at 1:32 PM

      Hello Frank, Both are same.

      Reply
  3. Gopal says

    August 29, 2015 at 9:46 AM

    Great tutorial, even for beginners. Sorted my array immediately.

    Reply
  4. ni says

    July 10, 2017 at 3:23 PM

    One question, does .sort retain existing order? This is often relevant. If you have it sorted by one criteria, then sort it by another criteria, do values by the second criteria which are equal still show the initial sort criteria is retained, or is the resulting order random?

    Reply

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap