Computer >> Computer tutorials >  >> Programming >> Java

Java Program to Sort Array list in an Ascending Order


In this article, we will understand how to sort array list in an ascending order. A list is an ordered collection that allows us to store and access elements sequentially. It contains the index-based methods to insert, update, delete and search the elements. It can also have the duplicate elements.

Below is a demonstration of the same −

Suppose our input is

Input list: [java, coding, is, fun]

The desired output would be

The sorted list is: [coding, fun, is, java]

Algorithm

Step 1 - START
Step 2 - Declare an ArrayList namely input_list.
Step 3 - Define the values.
Step 4 - Use the function Collections.sort() to sort the list.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

import java.util.*;
public class Demo {
   public static void main(String args[]){
      ArrayList<String> input_list = new ArrayList<String>();
      input_list.add("java");
      input_list.add("coding");
      input_list.add("is");
      input_list.add("fun");
      System.out.println("The list is defined as: " + input_list);
      Collections.sort(input_list);
      System.out.println("The sorted list is: " + input_list);
   }
}

Output

The list is defined as: [java, coding, is, fun]
The sorted list is: [coding, fun, is, java]

Example 2

Here, we encapsulate the operations into functions exhibiting object oriented programming.

import java.util.*;
public class Demo {
   static void sort(ArrayList<String> input_list){
      Collections.sort(input_list);
      System.out.println("The sorted list is: " + input_list);
   }
   public static void main(String args[]){
      ArrayList<String> input_list = new ArrayList<String>();
      input_list.add("java");
      input_list.add("coding");
      input_list.add("is");
      input_list.add("fun");
      System.out.println("The list is defined as: " + input_list);
      sort(input_list);
   }
}

Output

The list is defined as: [java, coding, is, fun]
The sorted list is: [coding, fun, is, java]