Comparable Natural Ordering With compareTo

Implement compareTo with Integer.compare and keep it consistent with equals so TreeSet, Stream.sorted, and sorted collections behave predictably.

JavaData Integrity

Code

snippet
import java.util.List;
import java.util.TreeSet;

public class NaturalOrdering {

    // compareTo 与 equals 一致(都只看 cents),TreeSet 的判重与排序才可预测
    record Price(int cents) implements Comparable<Price> {
        @Override
        public int compareTo(Price other) {
            // Integer.compare 防止减法比较在极端值下溢出
            return Integer.compare(this.cents, other.cents);
        }
    }

    public static void main(String[] args) {
        List<Price> quotes = List.of(new Price(990), new Price(150), new Price(990), new Price(250));

        TreeSet<Price> sorted = new TreeSet<>(quotes);
        System.out.println("lowest: " + sorted.first().cents());
        System.out.println("highest: " + sorted.last().cents());
        System.out.println("distinct prices: " + sorted.size());

        List<Price> sortedList = quotes.stream().sorted().toList();
        System.out.println("all quotes: "
                + sortedList.stream().map(price -> String.valueOf(price.cents())).toList());
    }
}

What the code does

The working surface is the classes NaturalOrdering and Price and the functions compareTo and main — everything else is wiring.

Data flows through a stream pipeline where each stage returns a new view rather than mutating.

Applying it

The main signature reads public int compareTo(Price other)

Running the file prints labeled results such as lowest:, highest:, distinct prices: — each operation’s effect is visible in the output.

Statements that matter

List<Price> sortedList = quotes.stream().sorted().toList();
return Integer.compare(this.cents, other.cents);

Interactive Tools for This Topic

FAQ

What does Comparable Natural Ordering With compareTo print when run?
The script runs standalone; its 4 labeled outputs include `lowest:`, `highest:`, `distinct prices:`.