1

pardon my english.

with this code,

 Collections.sort(mEntries, new Comparator<ZipEntry>() {
            public int compare(ZipEntry a, ZipEntry b) {
                return a.getName().compareTo(b.getName());
            }
        });

when there are strings like this: hello1,hello3,hello2,hello11,hello10

it will be sorted into this: hello1,hello10,hello11,hello2,hello3

the result i want is this:

hello1,hello2,hello3,hello10,hello11

but when there are strings with the same number digits like this, it can properly sort it.

from this: hello01,hello03,hello02,hello11,hello10.

into this: hello01,hello02,hello03,hello10,hello11

any idea how can i achieve the result i want?

hello1,hello2,hello3,hello10,hello11

thank you.

2 Answers2

0

The current sorting you are using is the natural (lexicographic) String sorting, derived by the invocation of compareTo on Strings.

According to lexicographic sorting, "10" comes before "2".

The sorting you want for Strings with the same radix, ending with digits is a numerical sorting, which is the natural sorting for Numbers (arithmetic).

According to the natural Number sorting, 10 will come after 2.

What you want is to:

  • Retrieve both Strings
  • Verify that their only difference is the last number (use regular expressions)
  • If not, compare them lexicographically as you're already doing
  • If instead, the only difference is the last number, then retrieve the last numbers and create two Integers (through regex and the Integer.parseInt idiom)
  • Then invoke the compareTo method on those Integers and return the outcome
Mena
  • 47,782
  • 11
  • 87
  • 106
0

nevermind, it works with this

  Collections.sort(mEntries, new Comparator<ZipEntry>() {
            public int compare(ZipEntry a, ZipEntry b) {


                return String.format("%100s", a.getName()).compareTo(
                        String.format("%100s", b.getName()));
            }
        });


        return null;

adopted from

how to sort with different number of digits in java?

Community
  • 1
  • 1
  • this will still sort based on the string, but not based on the numbers as per your requirement. do you confirm this fixes your requirement? – Mohamed Iqzas May 30 '16 at 10:05