Home >Java >javaTutorial >Collections.sort() in Java with Examples

Collections.sort() in Java with Examples

Patricia Arquette
Patricia ArquetteOriginal
2025-02-07 11:29:13320browse

Collections.sort() in Java with Examples

This article explores the Collections.sort() method in Java, a powerful tool for sorting elements within collections like lists and arrays. While a TreeSet can also sort elements, Collections.sort() offers flexibility and efficiency, especially when dealing with lists and other collection types. Located in the java.util.Collections class, this method primarily sorts elements in ascending order. It's an improvement over java.util.Arrays.sort(), capable of handling various collection types, including linked lists and queues.

Let's illustrate with an example:

Consider a list containing these strings:

<code>{"TutorialsPoint", "Friends", "Dear", "Is", "The", "Best", "Hey"}</code>

After applying Collections.sort(), the list becomes:

<code>{"Dear", "Best", "Friends", "Hey", "Is", "The", "TutorialsPoint"}</code>

Several methods facilitate sorting:

  • public void sort(List list): Sorts a list's elements. Crucially, the elements must implement the Comparable interface. This works well with strings and wrapper classes (like Integer).

  • sort(List list, Comparator c): Sorts a list using a custom Comparator to define the sorting order.

Algorithm for Using Collections.sort()

This algorithm outlines the steps to use Collections.sort() in a Java program:

  1. Start: Begin the process.
  2. Import Packages: Import necessary Java packages (e.g., java.util.*).
  3. Declare Class: Define a public class.
  4. Data Structure: Create a List (e.g., ArrayList).
  5. Populate List: Add data elements to the list.
  6. Sort: Use Collections.sort() to sort the list.
  7. Print: Display the sorted list.
  8. End: Terminate the process.

Syntax Examples

The following code snippets demonstrate Collections.sort() usage:

Example 1 (Sorting a list of custom objects):

<code class="language-java">class Fruit implements Comparable<fruit> {
    int id;
    String name, taste;

    Fruit(int id, String name, String taste) {
        this.id = id;
        this.name = name;
        this.taste = taste;
    }

    @Override
    public int compareTo(Fruit f) {
        return this.id - f.id;
    }

    // Getters for id, name, and taste
    public int getId() { return id; }
    public String getName() { return name; }
    public String getTaste() { return taste; }
}

// ... (rest of the code to create and sort a list of Fruit objects) ...</fruit></code>

Example 2 (Sorting a list of Integers):

<code class="language-java">ArrayList<integer> al = new ArrayList<>();
al.add(201);
al.add(101);
al.add(230);
Collections.sort(al); // Sorts in ascending order</integer></code>

Approaches

This article presents two approaches:

Approach 1: Demonstrating Collections.sort()

This approach shows how to sort an ArrayList in ascending order. The time complexity is O(N log N), and the auxiliary space is O(1).

Approach 2: Sorting with a Comparator

This approach demonstrates custom sorting using a Comparator interface, allowing for user-defined sorting criteria. Examples show sorting Student objects by roll number.

Performance Comparison (Arrays.sort() vs. Collections.sort())

A comparison of Arrays.sort() and Collections.sort() performance is included, highlighting the slight performance differences depending on the data size and type.

In conclusion, Collections.sort() provides a versatile and efficient way to sort various Java collections, offering both default ascending order and custom sorting capabilities through comparators. The choice between Arrays.sort() and Collections.sort() depends on the specific data structure and performance requirements.

The above is the detailed content of Collections.sort() in Java with Examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn