How To Sort A List In Java

Java is a powerful programming language, boasts an array of features that developers can utilize in the quest for programming supremacy. This language has earned its reputation for being both versatile and flexible. The most common responsibilities in the domain of data handling in Java programming is sorting.

Sorting, the systematic arrangement of a collection of components in a predetermined sequence, can be executed in a multitude of ways. This method is used to sort a list of elements depending on specific requirements.

In this blog we will explore different approaches and sample problems too.

Why is sorting a list in java needed?

Sorting a list in Java is an incredibly vital task that holds significant importance across several applications. The need for sorting a list can be attributed to a variety of reasons that are imperative for developers to understand.

  • Organization: The elements within a list are sorted, it significantly simplifies the process of searching for a specific item, and the data becomes more readable. This characteristic also lends itself to efficient data processing.
  • Efficiency: When attempting to search for an item within a large, unsorted list, the search algorithm would have to traverse the entire list, which is time consuming.
  • Presentation: Presentation is another crucial aspect where sorted lists shine. User interfaces that display data in a presentable manner often utilize sorted lists.
  • Analysis: Sorting a list can be helpful in data analysis as well. Sorting a list of numbers in either ascending or descending order can help identify patterns or trends within the data, making it an indispensable tool for various analysis purposes.

How To Sort A List In Java

There are six different approaches to sorting a list in java:

  1. Using the Collections.sort() method
  2. Using the Arrays.sort() method
  3. Using the List.sort() method
  4. Using the Comparator interface
  5. Using the Comparable interface
  6. Using the Stream.sorted() method

Let’s dive in more with examples to each approach.

Approach 1: Using the Collections.sort() method

The Collections.sort() method is a powerful utility that is instrumental in the sorting of elements belonging to a collection in ascending order. This method is used for sorting elements of List, Set, and other collections.

Pros:

  • Easy to use, requires no additional code
  • Works with any type of list, including user-defined types
  • Fast and efficient for small to medium-sized lists

Cons:

  • Cannot be used to sort a list in descending order without a custom Comparator
  • Not suitable for large lists as it has higher time complexity O(n log n)
  • Requires the entire list to be loaded into memory

Code:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(5, 3, 1, 4, 2));
        Collections.sort(list); // Sort the list
        System.out.println(list); // Print the sorted list
    }
}

Output:

[1, 2, 3, 4, 5]

Code Explanation:

  1. The code creates a list of integers using ArrayList and initializes it with five elements.
  2. This method helps us to sort the list in ascending order.
  3. The sorted list is printed to the console.

Approach 2: Using the Arrays.sort() method

The Arrays.sort() method is used to sort arrays of primitive data types and objects. This method sorts the elements of an array in ascending order.

Pros:

  • Works with any type of list, including user-defined types
  • Fast and efficient for small to medium-sized lists
  • Can be used to sort a list in descending order with a custom Comparator

Cons:

  • Requires extra code to convert list to array and back to list
  • Not suitable for large lists as it has higher time complexity O(n log n)
  • Requires the entire list to be loaded into memory

Code:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(5, 3, 1, 4, 2));
        Integer[] array = list.toArray(new Integer[0]); // Convert list to array
        Arrays.sort(array); // Sort the array
        list = Arrays.asList(array); // Convert array back to list
        System.out.println(list); // Print the sorted list
    }
}

Output:

[1, 2, 3, 4, 5]

Code Explanation:

  1. The code creates a list of integers using ArrayList and initializes it with five elements
  2. The list is converted to an array using the toArray() method
  3. This method helps us to sort the list in ascending order.
  4. The sorted array is converted back to a list using Arrays.asList() method
  5. The sorted list is printed to the console.

Approach 3: Using the List.sort() method

This method List.sort(), although similar to the Collections.sort() method, is implemented with the express purpose of ordering the constituent elements of a List.

Pros:

  • Easy to use, requires no additional code
  • Works with any type of list, including user-defined types
  • Fast and efficient for small to medium-sized lists

Cons:

  • Cannot be used to sort a list in descending order without a custom Comparator
  • Not suitable for large lists as it has higher time complexity O(n log n)
  • Requires the entire list to be loaded into memory

Code:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(5, 3, 1, 4, 2));
        Collections.sort(list); // Sort the list
        System.out.println(list); // Print the sorted list
    }
}

Output:

[1, 2, 3, 4, 5]

Code Explanation:

  1. We need to import the necessary packages to use List, ArrayList, Arrays, and Collections.
  2. We need to define a class with a main method where we put our code.
  3. We use Collections.sort() instead of list.sort() since sort() is not defined for List but only for specific implementations such as ArrayList.
  4. We need to use Collections.sort() instead of Arrays.sort() because Arrays.sort() works only with arrays and not with List.

Approach 4:Using the Comparator interface

The Comparator interface is used to sort elements of a collection in a customized order. This interface allows us to define our own sorting logic by implementing the compare() method.

Pros:

  • Can be used to sort a list in ascending or descending order
  • Works with any type of list, including user-defined types
  • Offers more flexibility than the built-in sorting methods

Cons:

  • Requires extra code to implement the comparison function
  • Not suitable for large lists as it has higher time complexity O(n log n)
  • Requires the entire list to be loaded into memory

Code:

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

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(5, 3, 1, 4, 2));
        Comparator<Integer> comparator = (a, b) -> b - a; // Define a custom comparator for descending order
        Collections.sort(list, comparator); // Sort the list using the custom comparator
        System.out.println(list); // Print the sorted list
    }
}

Output:

[5, 4, 3, 2, 1]

Code Explanation:

  1. The code creates a list of integers using ArrayList and initializes it with five elements
  2. A custom Comparator is defined to sort the list in descending order
  3. The Collections.sort() method is used to sort the list using the custom comparator
  4. The sorted list is printed to the console.

Approach 5: Using the Comparable interface

The Comparable interface is used to sort elements of a collection in the natural order. It is implemented by the class whose objects we want to sort. This interface has a compareTo() method that we need to override to provide our own sorting logic.

Pros:

  • Easy to use, requires no additional code
  • Works with any type of list, including user-defined types
  • Offers more flexibility than the built-in sorting methods

Cons:

  • Cannot be used to sort a list in descending order without a custom Comparator
  • Requires modifying the class of the list elements
  • Not suitable for large lists as it has higher time complexity O(n log n)

Code:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Person> list = new ArrayList<>(Arrays.asList(
            new Person("Alice", 25),
            new Person("Bob", 20),
            new Person("Charlie", 30)
        ));
        Collections.sort(list); // Sort the list based on age
        System.out.println(list); // Print the sorted list
    }
}

class Person implements Comparable<Person> {
    private String name;
    private int age;

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

    public int compareTo(Person other) {
        return this.age - other.age; // Compare based on age
    }

    public String toString() {
        return name + " (" + age + ")";
    }
}

Output:

[Bob (20), Alice (25), Charlie (30)]

Code Explanation:

  1. The code defines a Person class that implements the Comparable interface and provides a comparison function based on age
  2. A list of Person objects is created and initialized with three elements
  3. The Collections.sort() method is used to sort the list based on age using the default comparison function provided by the Person class
  4. The sorted list is printed to the console.

Approach 6: Using the Stream.sorted() method

The Stream.sorted() finds its primary function in the sorting of elements that are present within a given stream. This procedure operates by arranging the said elements in an ascending order, and it is worth noting that the resultant outcome is a brand new stream. This method is commonly used with Java 8 streams to perform operations on large datasets.

Pros:

  • Can be used to sort a list in ascending or descending order
  • Works with any type of list, including user-defined types
  • Offers more flexibility than the built-in sorting methods

Cons:

  • Requires extra code to implement the comparison function
  • Not suitable for large lists as it has higher time complexity O(n log n)
  • Requires the entire list to be loaded into memory

Code:

import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(5, 3, 1, 4, 2));
        Comparator<Integer> comparator = (a, b) -> b - a; // Define a custom comparator for descending order
        List<Integer> sortedList = list.stream().sorted(comparator).collect(Collectors.toList()); // Sort the list using the custom comparator
        System.out.println(sortedList); // Print the sorted list
    }
}

Output:

[5, 4, 3, 2, 1]

Code explanation:

  1. The code creates a list of integers using ArrayList and initializes it with five elements
  2. A custom Comparator is defined to sort the list in descending order
  3. The Stream.sorted() method is used to sort the list using the custom comparator, and the resulting stream is collected back into a List using the Collectors.toList() method
  4. The sorted list is printed to the console.

Best Approach For How To Sort A List In Java

The Collections.sort() method is the best approach to sort a list in java. Here are the some key features of this method are:

  • Fast and efficient: The Collections.sort() method is fast and efficient for small to medium-sized lists.
  • In-place sorting: The sort operation is performed in-place, meaning that the original list is modified rather than creating a new list object. This can be advantageous in terms of memory usage.
  • Stable sorting: The sort operation is stable, meaning that the order of equal elements in the list is preserved after sorting. This can be important in some applications.

Sample Problems For How To Sort A List In Java

Sample Problem 1:

Suppose you are building a social media platform that allows users to sort their friends list alphabetically. You have stored all the user’s friends in a List. However, the friends are not sorted alphabetically. You need to sort the List using the Collections.sort() method.

Solution Steps:

  1. Import the java.util package.
  2. Create a new class called “Main”.
  3. Inside the Main class, create the main method with the signature “public static void main(String[] args)”.
  4. Create a new List of type String called “friendsList” using the ArrayList class. This will store the names of the friends.
  5. Add the names of the friends to the List using the add() method.
  6. Use the Collections.sort() method to sort the List in alphabetical order. This method takes the List as an argument and automatically sorts it.
  7. Print the sorted List using the System.out.println() method. This will display the sorted List in the console.
  8. Close the main method and the class.

Code:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Step 1: Create a List of friends.
        List<String> friendsList = new ArrayList<String>();

        // Step 2: Add all the friends to the List.
        friendsList.add("Alice");
        friendsList.add("Bob");
        friendsList.add("Charlie");
        friendsList.add("David");
        friendsList.add("Eve");

        // Step 3: Use the Collections.sort() method to sort the List alphabetically.
        Collections.sort(friendsList);

        // Step 4: Print the sorted List.
        System.out.println("Sorted Friends List: " + friendsList);
    }
}

Output:

Sorted Friends List: [Alice, Bob, Charlie, David, Eve]

Sample Problem 2:

You are working as a sales manager in a company, and you need to sort a list of sales data based on the total sales amount. You can use the Arrays.sort() method to sort the list based on the total sales amount.

Solution Steps:

  1. Create a SalesData class with three private fields: name, month, and totalSalesAmount.
  2. Define a constructor for SalesData that takes name, month, and totalSalesAmount as parameters and initializes the fields.
  3. Implement getter methods for name, month, and totalSalesAmount fields.
  4. In the main method, create an array of SalesData objects.
  5. Populate the SalesData array with SalesData objects.
  6. Use Arrays.sort() method to sort the array in descending order of totalSalesAmount.
  7. Define a Comparator that compares two SalesData objects based on their totalSalesAmount.
  8. Implement the compare() method in the Comparator to compare two SalesData objects based on their totalSalesAmount.
  9. Iterate through the sorted array and print the name, month, and totalSalesAmount of each SalesData object.

Code:

import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        SalesData[] salesData = new SalesData[4];
        salesData[0] = new SalesData("John", "January", 10000);
        salesData[1] = new SalesData("Mike", "February", 20000);
        salesData[2] = new SalesData("Sara", "March", 5000);
        salesData[3] = new SalesData("Alex", "April", 30000);

        Arrays.sort(salesData, new Comparator<SalesData>() {
            @Override
            public int compare(SalesData s1, SalesData s2) {
                return s2.getTotalSalesAmount() - s1.getTotalSalesAmount();
            }
        });

        for (SalesData sales : salesData) {
            System.out.println(sales.getName() + " " + sales.getMonth() + " " + sales.getTotalSalesAmount());
        }
    }
}

class SalesData {
    private String name;
    private String month;
    private int totalSalesAmount;

    public SalesData(String name, String month, int totalSalesAmount) {
        this.name = name;
        this.month = month;
        this.totalSalesAmount = totalSalesAmount;
    }

    public String getName() {
        return name;
    }

    public String getMonth() {
        return month;
    }

    public int getTotalSalesAmount() {
        return totalSalesAmount;
    }
}

Output:

Alex April 30000
Mike February 20000
John January 10000
Sara March 5000

Sample Problem 3:

Imagine yourself as a data analyst who needs to sort a list of employee records based on their salaries.With the help of List.sort() method we can sort the list based on the salaries of the employees.

Solution steps:

  1. Create a class named “Employee” with private member variables “name” and “salary”.
  2. Add a constructor to the “Employee” class that takes in “name” and “salary” as parameters and sets them to the corresponding member variables.
  3. Add “getName()” and “getSalary()” methods to the “Employee” class that return the “name” and “salary” member variables, respectively.
  4. In the main method, create an empty ArrayList named “employeeList” that will store Employee objects.
  5. Add Employee objects to the “employeeList” using the “add()” method.
  6. Use the “sort()” method of the “employeeList” object to sort the list by the “salary” member variable of each Employee object.
  7. Use the “Comparator.comparing()” method to specify that the “salary” member variable should be used for sorting.
  8. Loop through the “employeeList” using a “for-each” loop and print out the name and salary of each Employee object using the “getName()” and “getSalary()” methods, respectively.
  9. Compile and run the program to see the sorted list of employees by their salaries.

Code:

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

public class Main {
    public static void main(String[] args) {
        List<Employee> employeeList = new ArrayList<Employee>();
        employeeList.add(new Employee("John", 50000));
        employeeList.add(new Employee("Mike", 30000));
        employeeList.add(new Employee("Sara", 40000));
        employeeList.sort(Comparator.comparing(Employee::getSalary));
        
        for(Employee emp : employeeList) {
            System.out.println(emp.getName() + " " + emp.getSalary());
        }
    }
}

class Employee {
    private String name;
    private int salary;
    
    public Employee(String name, int salary) {
        this.name = name;
        this.salary = salary;
    }
    
    public String getName() {
        return name;
    }
    
    public int getSalary() {
        return salary;
    }
}

Output:

Mike 30000
Sara 40000
John 50000

Sample Problem 4:

Suppose you are a doctor working in a hospital where you need to sort a list of patients based on their age. You can use the Comparator interface to sort the list based on the ages of the patients.

Solution Steps:

  1. Create a new Java class called Main with a main method.
  2. Inside the main method, create a new ArrayList of Patient objects called patientList.
  3. Add three Patient objects to the patientList using the add method.
  4. Use the Collections.sort method to sort the patientList in ascending order by age. This method takes two arguments: the list to be sorted and a Comparator object to define the sorting order.
  5. Create a new anonymous Comparator object by implementing the compare method, which takes two Patient objects and returns an integer representing their relative order. In this case, the compare method subtracts the age of the second Patient object from the age of the first Patient object to determine the order.
  6. Iterate over the sorted patientList using a for-each loop.
  7. For each Patient object, use the getName and getAge methods to print their name and age to the console.
  8. Create a new Java class called Patient with private instance variables name (a String) and age (an int).
  9. Create a constructor for the Patient class that takes a name and an age argument and initializes the corresponding instance variables.
  10. Create getName and getAge methods to retrieve the values of the name and age instance variables, respectively.
  11. Compile and run the Main class to see the sorted list of Patient objects printed to the console.

Code:

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

public class Main {
    public static void main(String[] args) {
        List<Patient> patientList = new ArrayList<>();
        patientList.add(new Patient("John", 25));
        patientList.add(new Patient("Mike", 35));
        patientList.add(new Patient("Sara", 30));
        
        Collections.sort(patientList, new Comparator<Patient>() {
            @Override
            public int compare(Patient p1, Patient p2) {
                return p1.getAge() - p2.getAge();
            }
        });
        
        for (Patient p : patientList) {
            System.out.println(p.getName() + " - " + p.getAge());
        }
    }
}

class Patient {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Output:

John - 25
Sara - 30
Mike - 35

Sample Problem 5:

Suppose you are a content creator who needs to sort a list of blog posts based on their publishing date. You can use the Comparable interface to sort the list based on the publishing date of the blog posts.

Solution Steps:

  1. Create a class called Student with two private fields: name and grade.
  2. Define a constructor for Student that takes name and grade as parameters and initializes the fields.
  3. Implement getName() and getGrade() methods to return the name and grade fields respectively.
  4. Override the toString() method to return a string representation of the Student object.
  5. Create a List of Student objects named studentList.
  6. Add three Student objects to studentList.
  7. Sort the studentList by the grade field in ascending order using the sorted() method and Comparator.comparing() method reference.
  8. Collect the sorted list into a new List called sortedList using the collect() method.
  9. Print the sortedList to the console using the System.out.println() method.

Code:

import java.time.LocalDate;
import java.util.*;

class BlogPost implements Comparable<BlogPost> {
private String title;
private LocalDate publishDate;
public BlogPost(String title, LocalDate publishDate) {
    this.title = title;
    this.publishDate = publishDate;
}

public String getTitle() {
    return title;
}

public LocalDate getPublishDate() {
    return publishDate;
}

@Override
public String toString() {
    return "Title: " + title + ", Publish Date: " + publishDate;
}

@Override
public int compareTo(BlogPost other) {
    return this.publishDate.compareTo(other.publishDate);
}
}

class Main {
public static void main(String[] args) {
List<BlogPost> blogPostList = new ArrayList<>();
    blogPostList.add(new BlogPost("Introduction to Java Programming", LocalDate.of(2023, 4, 1)));
    blogPostList.add(new BlogPost("Object-Oriented Programming Concepts", LocalDate.of(2023, 4, 3)));
    blogPostList.add(new BlogPost("Java Collections Framework", LocalDate.of(2023, 4, 2)));

    Collections.sort(blogPostList);

    System.out.println("Sorted Blog Posts:");
    for (BlogPost blogPost : blogPostList) {
        System.out.println(blogPost.getTitle() + " - " + blogPost.getPublishDate());
    }
}
}

Output:

Sorted Blog Posts:
Introduction to Java Programming - 2023-04-01
Java Collections Framework - 2023-04-02
Object-Oriented Programming Concepts - 2023-04-03

Sample Problem 6:

Suppose you are a teacher who needs to sort a list of students based on their grades. You can use the Stream.sorted() method to sort the list based on the grades of the students.

Solution Steps:

  1. Import the required classes for the program including the ArrayList, Comparator, and List classes from the java.util package.
  2. Create a Student class with name and grade fields, and their respective getters.
  3. Override the toString() method of the Student class to print the name and grade fields.
  4. Create a new ArrayList of Student objects named “studentList”.
  5. Add three Student objects to the “studentList” using the add() method.
  6. Create a new List object named “sortedList” by sorting the “studentList” using the sorted() method from the Stream class, which takes a Comparator.
  7. The Comparator.comparing() method is used to sort the “studentList” by the grade field of the Student objects, which is returned by the getGrade() method.
  8. The sorted List is collected into the “sortedList” using the collect() method of the Collectors class.
  9. Print the “sortedList” using the System.out.println() method.

Code:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("John", 85));
        studentList.add(new Student("Mike", 75));
        studentList.add(new Student("Sara", 90));
        List<Student> sortedList = studentList.stream()
                .sorted(Comparator.comparing(Student::getGrade))
                .collect(Collectors.toList());
        System.out.println(sortedList);
    }
}

class Student {
    private final String name;
    private final int grade;

    public Student(String name, int grade) {
        this.name = name;
        this.grade = grade;
    }

    public String getName() {
        return name;
    }

    public int getGrade() {
        return grade;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", grade=" + grade +
                '}';
    }
}

Output:

[Student{name='Mike', grade=75}, Student{name='John', grade=85}, Student{name='Sara', grade=90}]

Conclusion

After thorough analysis of the methods available for sorting a list in java, it becomes apparent that each approach boasts its own unique set of advantages and disadvantages.

The Collections.sort() method is often considered  as the most proficient method due to its flexibility and ease of use. It is important to choose the appropriate sorting method which depends on the needs of the project.