CodeGym /Java Blog /Java Collections /How to Sort a List in Java
Author
Jesse Haniel
Lead Software Architect at Tribunal de Justiça da Paraíba

How to Sort a List in Java

Published in the Java Collections group
Sorting arrays and lists is one of the most important problems of programming in general. That’s why it’s been solved in different ways a long time ago. Every modern popular programming language has some implementation of sorting methods. These implementations are usually well optimized and fast. However, it is said that newbie programmers should write such algorithms on their own, because it is beneficial for their programming skills. So it's pretty common for beginners to be asked to create a sorting algorithm during their learning or job interviews. In this article, we are going to talk about list sorting realization in Java language, as well as different sorting algorithms. We will also write one or two sorting algorithms on our own.

Sorting a List in Ascending Order with Collections.Sort() method

There are several ways to sort a list in Java. The most common (and logical!) way is to use the Collections.sort() method. This method sorts the elements of a list in ascending order by default. Ascending means different for different classes. For numbers it’s counting order (smaller number before the bigger one), for strings it’s alphabetical order. However, sorting rules can be different. You can also specify a comparator to sort the elements in a different order. To sort a list in Java in ascending order, you can use the Collections.sort() method without any arguments. The following code shows how to sort a list of strings in alphabetical order:

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

public class SimpleListSorting {
    public static void main(String[] args) {
        // Create a list of integers
        List<Integer> numbers = new ArrayList<>();
        numbers.add(5);
        numbers.add(1);
        numbers.add(3);
        numbers.add(2);

        // Display the original list
        System.out.println("Original list: " + numbers);

        // Sort ArrayList in ascending order
        Collections.sort(numbers);

        // Display the sorted list
        System.out.println("Sorted list (ascending): " + numbers);
    }
}
Here we have an unsorted list, using Collections.sort() method and print out sorted list.

List.Sort() Method and Comparator Usage

The Collections.sort() method is used for sorting a list in Java in the natural ordering of elements. For built-in data types like integers and strings, this means sorting in ascending order. However, when dealing with custom objects or complex sorting requirements, you can provide a custom comparator. A comparator is an implementation of the Comparator interface that defines a custom sorting logic. You can pass a comparator as the second argument to Collections.sort() to specify how elements should be compared and sorted. This flexibility allows you to sort objects based on specific attributes or criteria. Let’s create a class Student.

class Student2 {
   private String name;
   private int age;

   public Student2(String name, int age) {
       this.name = name;
       this.age = age;
   }

   public String getName() {
       return name;
   }

   public int getAge() {
       return age;
   }
}
Now let’s create a list of students and sort it out with the List.sort() method using a comparator.

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

   public class SortList {
       public static void main(String[] args) {
           List<Student2> students = new ArrayList<>();
           students.add(new Student2("Johnny", 11));
           students.add(new Student2("Ivy", 13));
           students.add(new Student2("Rick", 12));

           // Sort ArrayList of students by age in ascending order using a custom comparator
           Collections.sort(students, new Comparator<Student2>() {
               @Override
               public int compare(Student2 s1, Student2 s2) {
                   return Integer.compare(s1.getAge(), s2.getAge());
               }
           });

           // Display the sorted list of students
           for (Student2 student : students) {
               System.out.println(student.getName() + " - " + student.getAge() + " years old");
           }
       }
   }
The output with sorted list is here:
Johnny - 11 years old Rick - 12 years old Ivy - 13 years old
In this example, we create a custom comparator to sort a list of Student objects by their ages in ascending order. The Collections.sort() method, combined with custom comparators, offers great flexibility for sorting lists in Java, making it a valuable tool for various sorting tasks.

How to sort a list in Java 8 with Collections.Sort() using lambdas

Here's an example of how to sort a list of strings using List.sort() and lambda expressions in Java 8+:

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

public class Main {
    public static void main(String[] args) {
        // Create a list of string instruments in a quartet
        List<String> quartet = new ArrayList<>();
        quartet.add("Violin");
        quartet.add("Viola");
        quartet.add("Cello");
        quartet.add("Double Bass");

        // Display the original list
        System.out.println("Original quartet: " + quartet);

        // Sort the quartet using lambda expression (in ascending order)
        quartet.sort((instrument1, instrument2) -> instrument1.compareTo(instrument2));

        // Display the sorted quartet
        System.out.println("Sorted quartet (ascending): " + quartet);
    }
}
Here is the output:
Original quartet: [Violin, Viola, Cello, Double Bass] Sorted quartet (ascending): [Cello, Double Bass, Viola, Violin]

Sorted list without built-in method. What sorting algorithms are there?

In fact, there are a lot of sorting algorithms. Some of them are effective, others not so much. In Java, the built-in methods use a modification of the so-called Quick sort algorithm. It is very effective, but it will be difficult for a beginner to write it right away. It works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then sorted recursively. Here is Java implementation of Quick sort algorithm (it’s not the same sorting method as default, but somewhat close to it).

import java.util.List;
//our own quick sort() algorithm 
public class QuickSort {
    // Main sorting method to be called by the user
    public static void quickSort(List<Integer> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        quickSort(list, 0, list.size() - 1);
    }

    // Recursive helper method for Quick Sort
    private static void quickSort(List<Integer> list, int low, int high) {
        if (low < high) {
            // Find the partition index
            int partitionIndex = partition(list, low, high);

            // Recursively sort elements before and after the partition
            quickSort(list, low, partitionIndex - 1);
            quickSort(list, partitionIndex + 1, high);
        }
    }

    // Partitioning method to find the correct position of the pivot
    private static int partition(List<Integer> list, int low, int high) {
        // Choose the pivot element (in this case, the last element)
        int pivot = list.get(high);
        int i = low - 1;

        // Iterate through the list and move elements smaller than the pivot to the left
        for (int j = low; j < high; j++) {
            if (list.get(j) < pivot) {
                i++;
                swap(list, i, j);
            }
        }

        // Swap the pivot element to its correct position
        swap(list, i + 1, high);
        return i + 1;
    }

    // Helper method to swap two elements in the list
    private static void swap(List<Integer> list, int i, int j) {
        int temp = list.get(i);
        list.set(i, list.get(j));
        list.set(j, temp);
    }

    public static void main(String[] args) {
        List<Integer> numbers = List.of(7, 2, 1, 6, 8, 5, 3, 4);
        System.out.println("Unsorted List: " + numbers);
        quickSort(numbers);
        System.out.println("Sorted List: " + numbers);
    }
}
If you are a newbie, it could be pretty tough to write such a program. However there are some much more easy algorithms for sorting arrays and lists. For example classical Bubble sort algorithm. It’s a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. Bubble sort algorithm is easy to understand and implement, but it’s inefficient for large lists, especially in its basic form. Well, here is the implementation of the Bubble Sort algorithm.

public class BubbleSort {
//our own Bubble sort() algorithm 
        public static void bubbleSort(int[] myArray) {
            int n = myArray.length;
            for (int i = 0; i < n - 1; i++) {
                for (int j = 0; j < n - i - 1; j++) {
                    if (myArray[j] > myArray[j + 1]) {
                        // Swap myArray[j] and myArray[j+1]
                        int temp = myArray[j];
                        myArray[j] = myArray[j + 1];
                        myArray[j + 1] = temp;
                    }
                }
            }
        }

        public static void main(String[] args) {
            int[] arr = {18, 28, 2, 7, 90, 45};

            System.out.println("Array before sorting:");
            for (int num : arr) {
                System.out.print(num + " ");
            }

            bubbleSort(arr);

            System.out.println("\nArray after sorting:");
            for (int num : arr) {
                System.out.print(num + " ");
            }
        }
}
Here is the output:
Array before sorting: 18 28 2 7 90 45 Array after sorting: 2 7 18 28 45 90
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION