How to sort a list in Java : Explanation with example

How to sort a list in Java:

In this Java programming tutorial, we will learn how to sort a list . The program will sort the list and print it out again .

Let’s have a look at the program first :

Java program :

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


public class Main {

    //1
    private static void printList(List list){
        for(String item : list){
            System.out.print(item+" ");
        }
    }
    
    public static void main(String[] args){
        //2
        List items = new ArrayList<>();
        
        //3
        items.add("d");
        items.add("c");
        items.add("b");
        items.add("a");
        
        //4
        System.out.println("Items before sorted : ");
        printList(items);

        //5
        Collections.sort(items);

        //6
        System.out.println("\nItems after sorted : ");
        printList(items);
    }
}

Explanation :

The commented numbers in the above program denote the step numbers below :

  1. The function printList is used to print a list. It will take one List as input and print out its elements.

  2. Create one ArrayList that can hold strings.

  3. Add few characters to the list.

  4. Print out the list content to the user.

  5. Now,sort the list using the sort method of the Collections class.

  6. Finally print out the contents of the sorted list.

Sample Output:

Items before sorted : 
d c b a 
Items after sorted : 
a b c d 

Similar tutorials :