Java Programming Tutorials

Java programming tutorials with many code examples!

Java sort List

Problem:

How in Java sort List? Java allows to sort list elements using their natural ordering or using custom Comparators. In the following example we present both approaches.

Solution:

java.util.Collections has two sort methods:

  • <T extends Comparable<? super T>> void sort(List<T> list): sorts according to the natural ordering of the elements (strings, numbers, etc.)
  • <T> void sort(List<T> list, Comparator<? super T> c): sorts the list according to the ordering specified by the Comparator.

In the following example you can see both sort methods in use:

package com.farenda.java;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class CollectionsSort {

    public static void main(String[] args) {
        sortUsingDefaultComparator();

        System.out.println();

        sortUsingOwnComparator();
    }

    private static void sortUsingOwnComparator() {
        List<User> kings = new LinkedList<>(Arrays.asList(
                new User("Jagiełło"),
                new User("Batory"),
                new User("Chrobry"),
                new User("Sobieski")));
        Collections.shuffle(kings);
        System.out.println("Kings:");
        kings.forEach(System.out::println);

        System.out.println();

        List<User> sorted = new LinkedList<>(kings);
        Collections.sort(sorted, new NameComparator());
        System.out.println("Kings sorted by name:");
        sorted.forEach(System.out::println);

        System.out.println();

        sorted = new LinkedList<>(kings);
        Collections.sort(sorted, new IdComparator());
        System.out.println("Kings sorted by id:");
        sorted.forEach(System.out::println);
    }

    private static void sortUsingDefaultComparator() {
        List<Integer> temperatures = Arrays.asList(34, 30, 31, 30, 32, 35, 34);
        System.out.println("Temperatures: " + temperatures);

        Collections.sort(temperatures);
        System.out.println("Sorted: " + temperatures);
    }
}

Method sortUsingDefaultComparator() shows how Java sort List using default Comparator. In the second method sort is done using own Comparator.

The User class:

package com.farenda.java;

public class User {
    private static long userCounter;
    private long id;
    private final String name;

    public User(String name) {
        this.id = userCounter++;
        this.name = name;
    }

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "User(id:" + id + ", name: " + name + ")";
    }
}

Custom comparator that sorts Users by their names:

package com.farenda.java;

import java.util.Comparator;

/**
 * Compares Users using only their names.
 */
public class NameComparator implements Comparator<User> {
    @Override
    public int compare(User u1, User u2) {
        return u1.getName().compareTo(u2.getName());
    }
}

Another Comparator that sorts Users, but this time by their IDs:

package com.farenda.java;

import java.util.Comparator;

/**
 * Compares Users using only their Ids.
 */
public class IdComparator implements Comparator<User> {
    @Override
    public int compare(User u1, User u2) {
        return Long.compare(u1.getId(), u2.getId());
    }
}

Running the above Java example prints the following output:

Temperatures: [34, 30, 31, 30, 32, 35, 34]
Sorted: [30, 30, 31, 32, 34, 34, 35]

Kings:
User(id:3, name: Sobieski)
User(id:2, name: Chrobry)
User(id:0, name: Jagiełło)
User(id:1, name: Batory)

Kings sorted by name:
User(id:1, name: Batory)
User(id:2, name: Chrobry)
User(id:0, name: Jagiełło)
User(id:3, name: Sobieski)

Kings sorted by id:
User(id:0, name: Jagiełło)
User(id:1, name: Batory)
User(id:2, name: Chrobry)
User(id:3, name: Sobieski)
Share with the World!