Natural Sort Order in Java

After casually scouring the internet an afternoon for a method of sorting strings in a natural order, rather than an alphabetical one, I found the few implementations around lacking. Some ignored decimal numbers. Others included decimal numbers but ignored locale differences — e.g. different decimal points in different locales. Additionally, although it doesn’t appear in Wikipedia’s article on natural sorting, I also want my natural sort to ignore both case and, selectively, white space. I argue that follows if the goal is being a more “human friendly” way of sorting.

Update 2015-11-06

After a comment from someone whose name shall remain as anonymous as it is my brother’s, I added support for sorting grouped numbers (e.g. 1,000,000).

Update 2015-11-12

Since testing is all the rage I created and published the project to GitHub.

En reaktion till “Natural Sort Order in Java”

  1. Try this code. Testing with the Swedish currency format.

    NaturalOrderComparator comp = new NaturalOrderComparator();
    comp.compare(“abc”, “def”);
    comp.compare(“1 000 000 000,00”, “100 000 000,00”);

    First is correct. Returns -1.
    Second is incorrect. Returns -1. Should return 1.

Kommentera

E-postadressen publiceras inte. Obligatoriska fält är märkta *