Java Path compareTo() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 7+

Definition

In Java, a.compareTo(b) compares two paths lexicographically, like a dictionary. It returns a negative number when a comes first, 0 when the paths are equal, and a positive number when a comes after b. Path implements Comparable<Path>, so Collections.sort and TreeSet use this method.

Only the sign of the result is meaningful; the exact number depends on the platform. The order is the text order of the paths, so it does not sort folders first or numbers by value.

An instance method of the java.nio.file.Path interface, available since Java 7. Call it on a Path object, as in path.compareTo(...), after import java.nio.file.Path;.

Syntax

Compare with another path and test the sign:

Java
Path a = Paths.get("apple.txt");
Path b = Paths.get("banana.txt");
if (a.compareTo(b) < 0) {
    // a sorts before b
}
CallWhat it does
a.compareTo(b) < 0a sorts before b.
a.compareTo(b) == 0Equal paths; the same as a.equals(b).
Collections.sort(listOfPaths)Sorts with compareTo (natural order).

Since Java 7. On Linux and macOS the comparison is case-sensitive, byte by byte; on Windows it ignores case, so the same list can sort differently (Example 2).

Library declarations
Java
// java.nio.file.Path (interface), which extends Comparable<Path>
int compareTo(Path other)

Parameters

ParameterDescription
otherThe path to compare with. It must come from the same file system provider.

Return Value

Return ValueDescription
negative intThis path sorts before other.
0The paths are equal.
positive intThis path sorts after other.

Compare with Similar Methods

Related comparisons:

MethodHow it differs
equals()Just a yes/no answer; true exactly when compareTo returns 0.
String.compareTo()Orders plain text; similar on Linux, but Path ignores case on Windows.
Collections.sort()Sorts a list of paths using compareTo.

Java Examples

Outputs below are shown for Linux and macOS. On Windows, Java prints \ between names instead of /; the note above each output says when a result really differs.

Example 1 — Read the Sign of compareTo

Compare paths that sort before, after, and equal to each other, printing only the sign with Integer.signum.

Java
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathCompareToBasic {
    public static void main(String[] args) {
        Path apple = Paths.get("fruit/apple.txt");
        Path banana = Paths.get("fruit/banana.txt");
        System.out.println("apple vs banana: " + Integer.signum(apple.compareTo(banana)));
        System.out.println("banana vs apple: " + Integer.signum(banana.compareTo(apple)));
        System.out.println("apple vs apple:  " + Integer.signum(apple.compareTo(Paths.get("fruit", "apple.txt"))));
        System.out.println("short vs long:   " + Integer.signum(Paths.get("fruit").compareTo(apple)));
    }
}

How It Works

  1. The first different character decides. Both paths share fruit/, then a is compared with b; a is smaller, so apple sorts first and the sign is -1.
  2. Swap the order, flip the sign. banana.compareTo(apple) is positive, and an equal path built from parts gives 0, matching equals.
  3. A prefix sorts first. fruit is the beginning of fruit/apple.txt and is shorter, so it comes earlier; Integer.signum hides the platform-specific size of the difference.

Example 2 — Sort a List of Report Paths

Collections.sort puts paths in their natural order, which is the order of compareTo. Watch where README.md ends up.

Java
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PathCompareToSort {
    public static void main(String[] args) {
        List<Path> files = new ArrayList<>();
        files.add(Paths.get("reports/2026/mar.txt"));
        files.add(Paths.get("notes.txt"));
        files.add(Paths.get("reports/2025/dec.txt"));
        files.add(Paths.get("README.md"));
        files.add(Paths.get("reports/2026/jan.txt"));
        Collections.sort(files);
        for (Path f : files) {
            System.out.println(f);
        }
        System.out.println("first < last: " + (files.get(0).compareTo(files.get(4)) < 0));
    }
}

How It Works

  1. Natural order is compareTo. Collections.sort(files) needs no comparator, because Path is Comparable.
  2. Uppercase first on Linux and macOS. The comparison works on character codes, and R (82) is smaller than n (110), so README.md lands before notes.txt.
  3. Years sort as text. 2025 comes before 2026, and inside 2026 jan comes before mar only because j comes before m in the alphabet, not because of the calendar.

Example 3 — Fix the Order of Numbered File Names

Text order puts part10 before part2. A small comparator that first compares name length, then falls back to compareTo, gives the expected order.

Java
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class PathCompareToNumbers {
    public static void main(String[] args) {
        List<Path> parts = new ArrayList<>(Arrays.asList(
                Paths.get("part10.txt"), Paths.get("part2.txt"), Paths.get("part1.txt")));
        Collections.sort(parts);
        System.out.println("text order:   " + parts);
        Collections.sort(parts, (a, b) -> {
            int byLength = a.toString().length() - b.toString().length();
            return byLength != 0 ? byLength : a.compareTo(b);
        });
        System.out.println("number order: " + parts);
    }
}

How It Works

  1. Characters, not numbers. part1.txt and part10.txt share the start part1, then . (46) is smaller than 0 (48); part10 beats part2 because 1 is smaller than 2.
  2. Shorter names first. The lambda comparator sorts by text length, so the one-digit numbers part1 and part2 come before part10.
  3. compareTo breaks ties. Names of the same length fall back to a.compareTo(b); this simple trick only works when all names share the same prefix and extension.

Frequently Asked Questions

A negative int if this path sorts before the other, 0 if they are equal, and a positive int if it sorts after. Only the sign is meaningful.
Call Collections.sort(list) or list.sort(null). Path implements Comparable<Path>, so the natural order of compareTo is used.
compareTo compares text, character by character. The character 1 is smaller than 2, so part10 comes first. Use a custom comparator to sort numbers by value.
On Linux and macOS, yes: uppercase letters sort before lowercase ones. On Windows the comparison ignores case.
It throws ClassCastException when the paths belong to different file system providers, and NullPointerException when the argument is null.

Next: Path.endsWith()

Check whether a path ends with whole name elements, such as "docs/report.txt".

endsWith() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful