🌐
Minecraft Wiki
minecraft.fandom.com › wiki › Redstone_Comparator
Redstone Comparator – Minecraft Wiki
January 9, 2026 - A redstone comparator is a block that can produce an output signal from its front by reading chests, lecterns, beehives and similar blocks, or repeat a signal without changing its strength. It can also be set to either stop outputting a signal when its side input receives a stronger one (front ...
🌐
Minecraft
digminecraft.com › mechanism_recipes › make_redstone_comparator.php
How to make a Redstone Comparator in Minecraft
This is the Minecraft crafting recipe for a redstone comparator. Now that you have filled the crafting area with the correct pattern, the redstone comparator will appear in the box to the right. Once you have crafted a redstone comparator, you need to move the new item to your inventory. Congratulations, you have made a redstone comparator in Minecraft! Java ·
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 8 )
October 20, 2025 - 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.
🌐
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
🌐
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.
🌐
O'Reilly
oreilly.com › library › view › modern-java-recipes › 9781491973165 › ch04.html
Comparators and Collectors - Modern Java Recipes [Book]
August 16, 2017 - Java 8 also adds a new utility class called java.util.stream.Collectors, which provides static methods to convert from streams back into various types of collections. The collectors can also be applied “downstream,” meaning that they can postprocess a grouping or partitioning operation. The recipes in this chapter illustrate all these concepts. You want to sort objects. Use the sorted method on Stream with a Comparator, either implemented with a lambda expression or generated by one of the static compare methods on the Compa⁠rator interface.
Author   Ken Kousen
Published   2017
Pages   319
🌐
Oreate AI
oreateai.com › blog › minecraft-comparator-recipe › 5ce02d9e06e00d8e405d66de1f693456
Minecraft Comparator Recipe - Oreate AI Blog
January 7, 2026 - To craft a comparator in Minecraft Java Edition 1.20.3 (and beyond), you'll need three essential ingredients:
Find elsewhere
🌐
Tutorialspoint
tutorialspoint.com › home › java › java comparator example
Java Comparator Example
September 1, 2008 - Learn how to use the Java Comparator interface with examples. Understand sorting and comparison techniques in Java programming.
🌐
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 ...
🌐
Minecraft Wiki
minecraft.wiki › w › Redstone_Comparator
Redstone Comparator – Minecraft Wiki
The redstone comparator can take a signal strength input from its rear as well as from both sides. Side inputs are accepted only from redstone dust, block of redstone‌[Java Edition only], redstone repeaters, other comparators, and observers in specific scenarios.
🌐
Reddit
reddit.com › r/redstone › can someone explain to me how comparators work?
r/redstone on Reddit: Can someone explain to me how comparators work?
March 22, 2023 -

I literally don’t have a single clue and only now am I deciding to try and learn. Felt this sub could give the best explanation instead of some 20 min long YouTube tutorial video with 30 ads.

Top answer
1 of 13
12
Mostly copied from the wiki … A redstone comparator can: 1) Maintain signal strength A redstone comparator with no powered sides outputs the same signal strength as its rear input. Normally signal strength drops by 1 for each dust it goes through. Comparators can be used to get a specific signal strength from one place to another without loss. 2) Compare signal strength A redstone comparator in comparison mode (front torch down and unpowered, as initial placement) compares its rear input to its two side inputs. If either side input is greater than the rear input, the comparator output turns off. If neither side input is greater than the rear input, the comparator outputs the same signal strength as its rear input. Signal strength from the side must be from either dust, repeaters, comparators, or blocks of redstone (you can't transmit signal strength through a regular block to the side of a comparator, like you can with the back or front). Same for subtraction below: 3) Subtract signal strength A redstone comparator in subtraction mode (front torch up and powered, right-click to change) subtracts the signal strength of the higher side input from the signal strength of the rear input. 4) Measure block state A redstone comparator treats certain blocks behind it as power sources and outputs a signal strength proportional to the block's state. The comparator may be separated from the measured block by an opaque block. However, in Java Edition, if the opaque block is powered to signal strength 15, then the comparator outputs 15 no matter the fullness of the container. This is mostly used to measure the "fullness" of containers, but certain other blocks also give a signal.
2 of 13
6
Bedrock or Java?
🌐
Sportskeeda
wiki.sportskeeda.com › home › minecraft wiki
How to Craft a Redstone Comparator in Minecraft?
May 23, 2023 - Minecraft offers players a wide range of mechanisms and contraptions to explore and create. One such mechanism is the redstone comparator. In this tutorial, we will guide you through the process of crafting a redstone comparator in Minecraft, complete with step-by-step instructions.
🌐
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.
Top answer
1 of 3
4

Comparator#compare

What is the goal of the Comparator#compare method?

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

Given your formula of ( numOfWins2 - numOfWins1 ):

  • For the case of numOfWins1 = 30 and numOfWins2 = 20, ( 20 - 30 ) is -10, a negative number. So the first should be sorted after the second.
  • For the case of numOfWins1 = 20 and numOfWins2 = 30, ( 30 - 20 ) is 10, a positive number. So the first should be sorted above the second.
  • For the case of numOfWins1 = 25 and numOfWins2 = 25, ( 25 - 25 ) is 0, zero. So the two items are tied for sorting.

Complete example

Here is some example code. You can tweak the constructors of Alice and Carol to see the sorting in action.

This code uses the new compact record definition of a class, in Java 16+. But using record is beside the point of this Answer. You can just as well use a conventional class definition.

Copypackage work.basil.example;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Comparing
{
    public static void main ( String[] args )
    {
        Comparing app = new Comparing();
        app.demo();
    }

    private void demo ( )
    {
        List < FootballClub > clubs =
                List.of(
                        new FootballClub( "Alice" , 25 ) ,
                        new FootballClub( "Bob" , 7 ),
                        new FootballClub( "Carol" , 25 )
                );

        Comparator < FootballClub > sortByWinsDescending = new Comparator < FootballClub >()
        {

            public int compare ( FootballClub footballClub1 , FootballClub footballClub2 )
            {

                int numOfWins1 = footballClub1.wins();
                int numOfWins2 = footballClub2.wins();

                /* Returns the number of goals scored in  descending order */
                return numOfWins2 - numOfWins1;
            }
        };

        List < FootballClub > sorted = new ArrayList <>( clubs );
        sorted.sort( sortByWinsDescending );

        System.out.println( "clubs = " + clubs );
        System.out.println( "sorted = " + sorted );
    }

    record FootballClub(String name , Integer wins)
    {
    }
}

Not recommended

This code return ( numOfWins2 - numOfWins1 ) ; is the kind of “clever” programming that should be avoided. This code is confusing and troublesome. I even confused myself while writing this Answer.

Better would be letting objects compare themselves. In my example code, we use the class Integer. Well, Integer objects already know how to compare themselves. So call Integer#compareTo.

Copyreturn footballClub1.wins().compareTo( footballClub2.wins() ) ;

Or in the case of int primitives as seen in your code, call the static utility method Integer.compare( int x , int y ):

Copy        int numOfWins1 = footballClub1.getNumOfWins();
        int numOfWins2 = footballClub2.getNumOfWins();

        /* Returns the number of goals scored in  descending order */
        return Integer.compare ( numOfWins1 , numOfWins2 ) ;

By the way, we can look at the OpenJDK source code to see how this Integer.compare( int x , int y ) method is implemented. They use a nested pair of ternary operators. A ?: ternary works this way: If the predicate test is true, use item following the ?, else if false use the item following the :.

Copy// Copyright (c) 1994, 2020, Oracle and/or its affiliates. All rights reserved.
// Excerpt from https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/lang/Integer.java
// See licensing terms in that original file.
return (x < y) ? -1 : ((x == y) ? 0 : 1);

Make a habit of writing code this is as plain and simple as possible. Humans spend much more time reading code than writing code. On a job, when you have a bug in one of your report-generating methods, and you are debugging in the middle of the night, you do not want to be trying to figure out if return numOfWins2 - numOfWins1 is for ascending or descending.

As a bonus, plain and simple code that is readable by humans is often more likely to be an opportunity for the Java compiler and runtime to optimize for performance.


For fun, add this line before your return statement to see the individual comparisons.

CopySystem.out.println( "numOfWins1: " + numOfWins1 + " | numOfWins2: " + numOfWins2 + " | numOfWins2 - numOfWins1: " + ( numOfWins2 - numOfWins1 ) );

Ascending order

Tip: If you wanted ascending order rather than descending, just multiply the result of that call Integer#compareTo or Integer.compare by negative 1 (-1). Doing so flips the sign of the result, negative becomes positive, positive becomes negative, and zero remains zero.

Copyreturn ( -1 * Integer.compare ( numOfWins1 , numOfWins2 ) ) ;  // Ascending rather than descending sort order.

Method reference

As Ole V.V. commented, if you are comfortable with lambdas and method references, you can collapse your entire Comparator implementation to a single-line solution for ascending sort by calling Comparator.comparingInt.

CopyComparator < FootballClub > sortByWinsDescending = Comparator.comparingInt( FootballClub :: wins );

Our example above becomes quite shorter.

Copypackage work.basil.example;


import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Comparing2
{
    public static void main ( String[] args )
    {
        Comparing2 app = new Comparing2();
        app.demo();
    }

    private void demo ( )
    {
        List < FootballClub > clubs =
                List.of(
                        new FootballClub( "Alice" , 20 ) ,
                        new FootballClub( "Bob" , 7 ) ,
                        new FootballClub( "Carol" , 30 )
                );

        Comparator < FootballClub > sortByWinsDescending = Comparator.comparingInt( FootballClub :: wins );

        List < FootballClub > sorted = new ArrayList <>( clubs );
        sorted.sort( sortByWinsDescending );

        System.out.println( "clubs = " + clubs );
        System.out.println( "sorted = " + sorted );
    }

    record FootballClub(String name , Integer wins)
    {
    }
}

2 of 3
0

try this code:

Copy    public static Comparator<FootballClub> sortNumOfWins = new Comparator<FootballClub>() {

    public int compare(FootballClub footballClub1, FootballClub footballClub2) {

        Integer numOfWins1 = footballClub1.getNumOfWins();
        Integer numOfWins2 = footballClub2.getNumOfWins();

        return numOfWins2.compareTo(numOfWins1);
    }
};

when you compare integer field only and this compare is typical, you can use standard method compareTo from Integer type.

🌐
Baeldung
baeldung.com › home › java › guide to java comparator.comparing()
Guide to Java Comparator.comparing() | Baeldung
January 8, 2024 - In this tutorial, we’ll explore several functions introduced for the Comparator interface in Java 8.
🌐
Medium
medium.com › javarevisited › you-dont-know-comparators-in-practice-do-you-a9c029817378
You don’t know Comparators in-practice, Do You?
February 27, 2024 - Detailed GitHub documentation on Comparators — https://github.com/VarshaDas/Java-Code-Snippets/blob/main/ComparatorsDemo/README-Comparators.md
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.

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.