Combine alphabetical and natural order (aka. User sane sorting)

前端 未结 2 1178
伪装坚强ぢ
伪装坚强ぢ 2021-02-06 10:56

I thought this would be easy to find premade, but it seems any solution I can find on the web solves only part of the problem.

I want to sort a list of Filenames

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 11:23

    If you use the Comparator suggested by @millimoose (http://www.davekoelle.com/alphanum.html) modify it to pass the 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);
    ....
    

    this code seems to have a problem, for example "01" is grater then "2". But this depends on you preference, if this is important modify it to skip the leading zeros before number compare.

提交回复
热议问题