Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java sort List

farenda 2015-08-13 0

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!
Categories Java Tags java-collections
Previous: Java singleton List
Next: Java List swap

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok