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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Comparing digit runs as whole numbers instead of character-by-character produces human-friendly ordering.
- 2A shared stateless comparator instance is safe to expose as a singleton constant.
- 3Comparator.comparing plus thenComparing lets you layer a custom key extractor into richer sort orders.
Related explainers
java
package com.example.validation; import java.util.List; import java.util.stream.Collectors;
Validating JSON payloads against a schema in Java
json-schema
validation
recursion
Intermediate
8 steps
java
public URI buildSearchUri(String query, int page, int size, List<String> tags) { UriComponentsBuilder builder = UriComponentsBuilder .fromUriString("https://api.example.com") .path("/v2/products/search")
Building URIs safely with UriComponentsBuilder in Spring
url-building
builder-pattern
encoding
Intermediate
5 steps
java
@Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
Real-time chat over STOMP WebSockets in Spring
websockets
stomp
messaging
Intermediate
8 steps
java
@Configuration @EnableRedisHttpSession(namespace = "myapp:sessions", maxInactiveIntervalInSeconds = 1800, flushMode = FlushMode.IMMEDIATE) public class SessionConfig {
Backing HTTP sessions with Redis in Spring
session-management
redis
distributed-state
Intermediate
7 steps
java
public List<User> findUsersByEmailDomain(String domain, int minAge) { String sql = """ SELECT id, username, email, age, created_at FROM users
Safe parameterized JDBC queries in Java
jdbc
sql-injection
prepared-statement
Intermediate
7 steps
java
@Configuration @EnableBatchProcessing public class CustomerImportJobConfig {
How a chunk-based CSV import job works in Spring
batch-processing
etl
csv-parsing
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/natural-order-string-sorting-in-java-explained-java-eac8/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.