Java – find a combination of alphabetical and natural order (also known as user rational sorting)

I think it's easy to find premade, but it seems that any solution I find online can only solve part of the problem

I want to list the file names provided by users (most of the files are named by people and / or addresses), sometimes in different languages (most of them are German, a little mixed with French and Italian), and there are few other Western languages)

Our idea is to present this list in a way that (German) users generally think rational This means that the order should follow locale German's Java text. Collator, but it is also expected to exception the number in the string, so "10" is after "2"

I found the code for natural sorting on the Internet, but it relies on character by character comparison (which collator does not support) I can use substrings to crack some content, but inside the comparator, I don't think it's the wisest idea to create multiple substrings every comparison call

How can any idea effectively achieve this (in execution time and implementation time), or better, a tested and ready to use implementation?

Solution

If you use @ millimoose recommended comparator( http://www.davekoelle.com/alphanum.html )Modify it to pass collator

public class AlphanumComparator implements Comparator
{
private Collator collator;
public AlphanumComparator(Collator collator) {
    this.collator = collator;
}
.....
    public int compare(Object o1,Object o2)
    {
......
result = thisChunk.compareTo(thatChunk); //should become
collator.compare(thisChuck,thatChuck);
....

There seems to be a problem with this code, for example, "01" is larger, and then "2" However, it depends on your preference. If this is important, please modify it to skip leading zeros before number comparison

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>