🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 8 )
October 20, 2025 - Unlike Comparable, a comparator may optionally permit comparison of null arguments, while maintaining the requirements for an equivalence relation. This interface is a member of the Java Collections Framework.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-comparator-interface
Java Comparator Interface - GeeksforGeeks
The Comparator interface in Java is used to define custom sorting logic for objects. It belongs to java.util package allows sorting of objects of user-defined classes without modifying their source code.
Published   April 20, 2016
🌐
Baeldung
baeldung.com › home › java › core java › comparator and comparable in java
Comparator and Comparable in Java | Baeldung
March 26, 2025 - We can build one simply by making use of the Comparator or Comparable interfaces. Let’s use an example of a football team, where we want to line up the players by their rankings. ... public class Player { private int ranking; private String name; private int age; // constructor, getters, setters }
🌐
W3Schools
w3schools.com › java › java_advanced_sorting.asp
Java Advanced Sorting (Comparator and Comparable)
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... In the List Sorting Chapter, you learned how to sort lists alphabetically and numerically, but what if the list has objects in it? To sort objects you need to specify a rule that decides how objects should be sorted. For example, if you have a list of cars you might want to sort them by year, the rule could be that cars with an earlier year go first. The Comparator and Comparable interfaces allow you to specify what rule is used to sort objects.
🌐
Tutorialspoint
tutorialspoint.com › home › java › java comparator example
Java Comparator Example
September 1, 2008 - In Java, the Comparator interface is a part of java.util package and it defines the order of the objects of user-defined classes.
🌐
Oracle
docs.oracle.com › javase › › 7 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 7 )
Java™ Platform Standard Ed. 7 ... A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order.
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › docs › api › java.base › java › util › Comparator.html
Comparator (Java SE 21 & JDK 21)
October 20, 2025 - Unlike Comparable, a comparator may optionally permit comparison of null arguments, while maintaining the requirements for an equivalence relation. This interface is a member of the Java Collections Framework.
🌐
DigitalOcean
digitalocean.com › community › tutorials › comparable-and-comparator-in-java-example
Comparable and Comparator in Java Example | DigitalOcean
August 3, 2022 - Comparator interface compare(Object o1, Object o2) method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if the first argument is less than the second one and returns zero if they are equal and positive int if the first argument is greater than the second one. Comparable and Comparator interfaces use Generics for compile-time type checking, learn more about Java Generics.
🌐
Oracle
docs.oracle.com › javase › 6 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 6)
Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S.
Find elsewhere
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › util › Comparator.html
Comparator (Java SE 17 & JDK 17)
January 20, 2026 - Unlike Comparable, a comparator may optionally permit comparison of null arguments, while maintaining the requirements for an equivalence relation. This interface is a member of the Java Collections Framework.
🌐
Jenkov
jenkov.com › tutorials › java-collections › comparator.html
Java Comparator
The Java Comparator interface, java.util.Comparator, represents a component that can compare two objects so they can be sorted using sorting functionality in Java. When sorting e.g a Java List you can pass a Java Comparator to the sorting method.
🌐
Codecademy
codecademy.com › docs › java › comparator
Java | Comparator | Codecademy
July 28, 2025 - Comparator in Java is an interface used to order objects of an arbitrary class. It is not to be confused with the Comparable interface, which is implemented by the class to be sorted.
Top answer
1 of 16
242

There are a couple of awkward things with your example class:

  • it's called People while it has a price and info (more something for objects, not people);
  • when naming a class as a plural of something, it suggests it is an abstraction of more than one thing.

Anyway, here's a demo of how to use a Comparator<T>:

public class ComparatorDemo {

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person("Joe", 24),
                new Person("Pete", 18),
                new Person("Chris", 21)
        );
        Collections.sort(people, new LexicographicComparator());
        System.out.println(people);
        Collections.sort(people, new AgeComparator());
        System.out.println(people);
    }
}

class LexicographicComparator implements Comparator<Person> {
    @Override
    public int compare(Person a, Person b) {
        return a.name.compareToIgnoreCase(b.name);
    }
}

class AgeComparator implements Comparator<Person> {
    @Override
    public int compare(Person a, Person b) {
        return a.age < b.age ? -1 : a.age == b.age ? 0 : 1;
    }
}

class Person {

    String name;
    int age;

    Person(String n, int a) {
        name = n;
        age = a;
    }

    @Override
    public String toString() {
        return String.format("{name=%s, age=%d}", name, age);
    }
}

EDIT

And an equivalent Java 8 demo would look like this:

public class ComparatorDemo {

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person("Joe", 24),
                new Person("Pete", 18),
                new Person("Chris", 21)
        );
        Collections.sort(people, (a, b) -> a.name.compareToIgnoreCase(b.name));
        System.out.println(people);
        Collections.sort(people, (a, b) -> a.age < b.age ? -1 : a.age == b.age ? 0 : 1);
        System.out.println(people);
    }
}
2 of 16
202

Here's a super short template to do the sorting right away :

Collections.sort(people, new Comparator<Person>() {
   @Override
   public int compare(final Person lhs, Person rhs) {
     // TODO return 1 if rhs should be before lhs 
     //      return -1 if lhs should be before rhs
     //      return 0 otherwise (meaning the order stays the same)
   }
 });

If it's hard to remember, try to just remember that it's similar (in terms of the sign of the number) to:

 lhs-rhs 

That's in case you want to sort in ascending order : from smallest number to largest number.

🌐
Dev.java
dev.java › learn › writing-and-combining-comparators
Dev
Launching simple source-code Java programs with the Java launcher. ... jshell interactively evaluates declarations, statements, and expressions of the Java programming language in a read-eval-print loop (REPL).
🌐
Javatpoint
javatpoint.com › Comparator-interface-in-collection-framework
Java Comparator - javatpoint
Java Comparator interface is used to order the user-defined class objects, compare() method, collection class, java comporator example, Example of Comparator interface in collection framework.
🌐
Medium
medium.com › @pratik.941 › understanding-comparable-and-comparator-interface-in-java-their-role-in-sorting-4338b3017fa9
Understanding Comparable and Comparator interface in Java: Their Role in Sorting | by Pratik T | Medium
October 4, 2024 - The compare() method compares two objects and returns: — A negative integer if the first argument is less than the second. — Zero if the first argument is equal to the second. — A positive integer if the first argument is greater than the second. ... import java.util.Comparator; public class Student { private String name; private int rollNumber; public Student(String name, int rollNumber) { this.name = name; this.rollNumber = rollNumber; } public String getName() { return name; } public int getRollNumber() { return rollNumber; } @Override public String toString() { return "Student{name='
Top answer
1 of 5
17

EDIT: First of all, a couple of things:

  1. The @Override annotation should not be mandatory. If Eclipse wants you to put it on, don't worry.
  2. Don't write your own Comparator interface. Delete that definition NAO and use the one provided by Java. Reinventing the wheel probably violates the Unspoken Code of Computer Programming in about 15 different ways. Use import java.util.Comparator; at the very top of your code (before the public class stuff) to a) use the version given by Java and b) make your code compatible with pretty much everything else that exists in the world.

The Comparator interface is not used to create a class that can put itself in order. This is the Comparable interface.

Both are similar, so I will describe both here.

java.util.Comparator

The Comparator interface, as you already know, has one method: compare. Comparator is generic (uses the angle brackets <>) and takes the type it will compare inside the <>. The thing is that Comparators are used to compare items of other classes. For example, I could create a Comparator for java.lang.Integers that returns the opposite of the "natural order" (how Integers are usually ordered).

Comparators are used mostly to give other objects a way to sort their parameters when they are not in natural order. For example, the java.util.TreeSet class takes a Comparator for its sorting capability.

java.lang.Comparable

Comparable's purpose is to say that an object can be compared. It is also generic and takes the type that it can be compared to. For example, a Comparable<String> can be compared to Strings.

Comparable has one method: compareTo(). Unlike Comparator's compare(), compareTo takes one parameter. It works like compare, except it uses the invoking object as one parameter. So, comparableA.compareTo(comparableB) is the same as comparator.compare(comparableA, comparableB).

Comparable mostly establishes the natural order for objects, and is the default way to compare objects. Comparator's role is to override this natural order when one has different needs for data comparison or sorting.

ArrayList Sorting

To sort a List, you could use the method already available: scroll down to sort on the java.util.Collections class. One method takes a Comparator, the other does not. sort is static; use Collections.sort(...), not Collections c = new Collections(); c.sort(...). (Collections doesn't even have a constructor anyway, so meh.)

2 of 5
12

To use the Comparator interface you have to implement it and pass it as an anonymous class to Collections.sort(List list, Comparator c) as the second parameter.

If you want to pass only the list to Collections.sort(List list) then your Item class has to the implement Comparable interface.

So in both cases the Collections.sort methods know how to order the elements in your list

here is some sample code:

Item class implementing Comparable + Inventory holding a list of items

Copypublic class Item implements Comparable<Item> {

    String id = null;

    public Item(String id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return id;
    }

    @Override
    public int compareTo(Item o) {
        return - id.compareToIgnoreCase(o.id);
    }
}


public class Inventory {

    List<Item> items = new ArrayList<>();

    public void addItem(Item item) {
        items.add(item);
    }

    public static void main(String[] args) {
        Inventory inventory = new Inventory();
        inventory.addItem(new Item("2"));
        inventory.addItem(new Item("4"));
        inventory.addItem(new Item("1"));
        inventory.addItem(new Item("7"));

        Collections.sort(inventory.items, new Comparator<Item>() {
            @Override
            public int compare(Item o1, Item o2) {
                return o1.id.compareToIgnoreCase(o2.id);
            }
        });
        System.out.println(inventory.items);

        Collections.sort(inventory.items);
        System.out.println(inventory.items);

    }
}

Output

Copy[1, 2, 4, 7] // ascending
[7, 4, 2, 1] // descending since the compareTo method inverts the sign of the comparison result.
🌐
Scaler
scaler.com › home › topics › java › comparable and comparator in java
Difference between Comparable and Comparator in Java - Scaler Topics
July 13, 2023 - Comparable and Comparator in Java allow us to define custom sorting behavior for objects, including sorting based on multiple data members.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › util › Comparator.html
Comparator (Java SE 11 & JDK 11 )
January 20, 2026 - Unlike Comparable, a comparator may optionally permit comparison of null arguments, while maintaining the requirements for an equivalence relation. This interface is a member of the Java Collections Framework.
🌐
Oracle
docs.oracle.com › en › java › javase › 18 › docs › api › java.base › java › util › Comparator.html
Comparator (Java SE 18 & JDK 18)
August 18, 2022 - Unlike Comparable, a comparator may optionally permit comparison of null arguments, while maintaining the requirements for an equivalence relation. This interface is a member of the Java Collections Framework.