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
- Start with Two paths both spelled a.txt
- Do this Compare the path values
- Result Equal
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.javaDeduplicate 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.
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());
}
}
true 0 true
Equal paths compare as zero and have equal hash codes, which makes them suitable set keys.
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.
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()));
}
}
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?
What to watch for
Provider-specific case and ordering rules apply. For two existing names that may identify the same file, use Files.isSameFile.