Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numeric comparing option for Java Collator

Problem:

Let's say we have the following list of strings {"Test1.txt", "Test2.txt", "Test11.txt", "Test22.txt"}, sorting them using String::compareTo or Collator::compare would result in following order:

Test1.txt
Test2.txt
Test22.txt
Test3.txt

Which is inconvenient(arguably), while a more human-friendly outcome is:

Test1.txt
Test2.txt
Test3.txt
Test22.txt

To resolve this issues we can write our own compare method which is numeric sensitive. But what if we want numeric sensitive sort as well as the benefit of using existing implementation of Collator (or to avoid implementing one) for internationalization?

Is there a right way to handle this? or maybe a reliable library that addresses this problem?

Other Languages:

In Javascript world the Intl.Collator's constructors accepts a CollatorOption which allows you to set configs to achieve such functionality and more:

const usCollator = Intl.Collator("us", { numeric: true });
const list = ["Test1.txt", "Test2.txt", "Test3.txt", "Test22.txt"];
list.sort(usCollator.compare);
console.log(list);
like image 811
Alireza Dastyar Avatar asked Aug 13 '26 06:08

Alireza Dastyar


1 Answers

You can use alphanumeric-comparator, which is available in Maven.

like image 166
MikeFHay Avatar answered Aug 15 '26 19:08

MikeFHay