java 53 lines · 9 steps

Natural-order string sorting in Java

A comparator that sorts strings the way humans read them, treating digit runs as whole numbers so "file2" comes before "file10".

Explained by highlit
1public final class NaturalOrderComparator implements Comparator<String> {
2 
3 public static final NaturalOrderComparator INSTANCE = new NaturalOrderComparator();
4 
5 @Override
6 public int compare(String a, String b) {
7 int i = 0, j = 0;
8 while (i < a.length() && j < b.length()) {
9 char ca = a.charAt(i);
10 char cb = b.charAt(j);
11 
12 if (Character.isDigit(ca) && Character.isDigit(cb)) {
13 int endA = skipDigits(a, i);
14 int endB = skipDigits(b, j);
15 int cmp = compareNumeric(a, i, endA, b, j, endB);
16 if (cmp != 0) return cmp;
17 i = endA;
18 j = endB;
19 } else {
20 int cmp = Character.compare(
21 Character.toLowerCase(ca), Character.toLowerCase(cb));
22 if (cmp != 0) return cmp;
23 i++;
24 j++;
25 }
26 }
27 return Integer.compare(a.length() - i, b.length() - j);
28 }
29 
30 private static int skipDigits(String s, int start) {
31 int k = start;
32 while (k < s.length() && Character.isDigit(s.charAt(k))) k++;
33 return k;
34 }
35 
36 private static int compareNumeric(String a, int as, int ae, String b, int bs, int be) {
37 while (as < ae && a.charAt(as) == '0') as++;
38 while (bs < be && b.charAt(bs) == '0') bs++;
39 int lenA = ae - as, lenB = be - bs;
40 if (lenA != lenB) return Integer.compare(lenA, lenB);
41 for (int k = 0; k < lenA; k++) {
42 int cmp = Character.compare(a.charAt(as + k), b.charAt(bs + k));
43 if (cmp != 0) return cmp;
44 }
45 return 0;
46 }
47 
48 public static Comparator<Path> byFileName() {
49 return Comparator.comparing(
50 (Path p) -> p.getFileName().toString(), INSTANCE)
51 .thenComparing(p -> p.getParent() == null ? "" : p.getParent().toString(), INSTANCE);
52 }
53}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Comparing digit runs as whole numbers instead of character-by-character produces human-friendly ordering.
  2. 2A shared stateless comparator instance is safe to expose as a singleton constant.
  3. 3Comparator.comparing plus thenComparing lets you layer a custom key extractor into richer sort orders.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Natural-order string sorting in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code