Library contents

Java Path equality and ordering

Compare path objects or use a path as a set key without opening a file.

A simple example

Path equality and ordering

  1. Start with Two paths both spelled a.txt
  2. Do this Compare the path values
  3. Result Equal
Identically formed path values compare equal. This comparison needs no file contents.

Syntax

Java syntax
int compareTo(Path other)
JDK 21 declarations (3)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Deduplicate a list of classroom handouts

A teacher imports the same worksheet name from two lists. Before downloading anything, the organizer should keep a single entry for the repeated path and confirm its ordering against itself.

From the programPath a = Path.of("lab", "sheet.pdf")
First output linetrue
Main.java
import java.nio.file.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path a = Path.of("lab", "sheet.pdf");
        Path b = Path.of("lab").resolve("sheet.pdf");
        System.out.println(a.equals(b));
        System.out.println(a.compareTo(b));
        System.out.println(a.hashCode() == b.hashCode());
    }
}
Output
true
0
true

Equal paths compare as zero and have equal hash codes, which makes them suitable set keys.

Advertisements

Compare a raw name with its normalized form

A catalog imports one path containing a redundant current-directory component. Compare it before and after normalization to decide whether the catalog should normalize keys before deduplicating them.

From the programPath clean = Path.of("course", "notes.txt")
First output linefalse
Main.java
import java.nio.file.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path clean = Path.of("course", "notes.txt");
        Path raw = Path.of("course", ".", "notes.txt");
        System.out.println(clean.equals(raw));
        System.out.println(clean.equals(raw.normalize()));
    }
}
Output
false
true

Lexically different component sequences become equal after removing the redundant component.

Locate a rehearsal score

The choir stores each score inside a season folder. Two labels are built with the same parent and final name. Will their normalized path values compare equal?

Givenspring / alto.txt
Worked resultEqual

What to watch for

Provider-specific case and ordering rules apply. For two existing names that may identify the same file, use Files.isSameFile.

Documentation for Path equality and ordering