SoFunction
Updated on 2025-03-08

How to sort elements of a collection in Java

In Java, sorting collection elements is a common operation and can be implemented in many ways. Here are several common methods to sort elements in a collection.

1. Use()Sort List

()It is a common method in Java, used to matchListThe elements in it are sorted. It usesComparableInterface or providedComparatorInterface to sort.

Sort in natural order (elements must be implementedComparableinterface)

For example, sort aList<Integer>

import .*;
public class SortExample {
    public static void main(String[] args) {
        List&lt;Integer&gt; numbers = new ArrayList&lt;&gt;();
        (5);
        (3);
        (8);
        (1);
        // Use () to sort in natural order        (numbers);
        ("Sorted List: " + numbers);
    }
}

Output

Sort by list: [1, 3, 5, 8]

useComparatorCustom sorting

If you want to use a custom sorting rule, you can pass aComparatorObject:

import .*;
public class SortExample {
    public static void main(String[] args) {
        List&lt;String&gt; names = new ArrayList&lt;&gt;();
        ("Alice");
        ("Bob");
        ("Charlie");
        ("Dave");
        // Sort by string length        (names, (a, b) -&gt; ((), ()));
        ("Sorted List: " + names);
    }
}

Output

Sort by list: [Bob, Dave, Alice, Charlie]

2. Use()Methods to sort

Starting with Java 8,ListNew interface addedsort()Method, it is also based onComparatorSort by. You can be like()Provide oneComparator

import .*;
public class SortExample {
    public static void main(String[] args) {
        List&lt;Integer&gt; numbers = new ArrayList&lt;&gt;();
        (5);
        (3);
        (8);
        (1);
        // Use the () method to sort        (Integer::compareTo);
        ("Sorted List: " + numbers);
    }
}

Output

Sort by list: [1, 3, 5, 8]

3. UseStreamAPI sorting

Java 8 has introducedStreamAPI, which can also be used to sort collections and return a new sorted stream.

import .*;
import .*;
public class SortExample {
    public static void main(String[] args) {
        List&lt;Integer&gt; numbers = (5, 3, 8, 1);
        // Sort using Stream        List&lt;Integer&gt; sortedNumbers = ()
                                             .sorted()
                                             .collect(());
        ("Sorted List: " + sortedNumbers);
    }
}

Output

Sort by list: [1, 3, 5, 8]

4. SortMapKey or value of

If you have oneMap(likeHashMap) and need to be sorted by key or value, you can useentrySet()Methods andComparatorSort.

Key sorting:

import .*;
public class SortMapExample {
    public static void main(String[] args) {
        Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();
        ("Alice", 30);
        ("Bob", 25);
        ("Charlie", 35);
        // Sort by key        ()
           .stream()
           .sorted(())
           .forEach(entry -&gt; (() + ": " + ()));
    }
}

Output

Alice: 30
Bob: 25
Charlie: 35

Sort by value:

import .*;
public class SortMapExample {
    public static void main(String[] args) {
        Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();
        ("Alice", 30);
        ("Bob", 25);
        ("Charlie", 35);
        // Sort by value        ()
           .stream()
           .sorted(())
           .forEach(entry -&gt; (() + ": " + ()));
    }
}

Output

Bob: 25
Alice: 30
Charlie: 35

Summarize:

  • (): Applicable toList, in natural order or using customComparatorSort.
  • (): Methods starting with Java 8, based onComparatorSort.
  • ():useStreamThe API sorts, returning the sorted stream.
  • MapSort: Can be usedentrySet()andComparatorrightMapkeys or values ​​are sorted.

These methods can select appropriate ways to sort elements in the set according to specific needs.

This is the end of this article about how to sort the elements of a collection in Java. For more related Java collection element sorting content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!