Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort numbers with leading zeros in Java?

Hi I have String list as input with leading zeros and I am wondering how to sort them.

Input(unsorted)

0-2
0-1
1
1-2
1-0
1-1
4-3

Output(sorted)

0-1
0-2
1
1-0
1-1
1-2
4-3

I can remove "-" and leading zeroes but then 0-1 -> 1 and 1 -> 1 are the same and can not be sorted. Other thing that comes in my mind is to remove the zero and in these numbers that have not leading zero to put 0 behind so

0-1->1
1->10
10->100

then use Java sort and the back numbers in the start position but sorted?

Edit:

  • Structure is unlimited in depth so 1-2-3-4-5-6...
  • I can have only one leading 0
  • Only dash(-) and point (.) are allowed decimeters.
like image 749
Xelian Avatar asked Sep 17 '15 15:09

Xelian


1 Answers

I'd split the string by the - character and then convert each part to an int:

public class StringPartsComparator implements Comparator<String> {

    @Override
    public int compare (String s1, String s2) {
        String[] arr1 = s1.split("-");
        int len1 = arr1.length;

        String[] arr2 = s2.split("-");
        int len2 = arr2.length;

        int commonLength = Math.min(len1, len2);

        // Go over the "common" elements.
        // Return if any element differs from its counterpart
        for (int i = 0; i < commonLength; ++i) {
            int int1 = Integer.parseInt(arr1[i]);
            int int2 = Integer.parseInt(arr2[i]);
            int comp = Integer.compare(int1, int2);
            if (comp != 0) {
                return comp;
            }
        }

        // All the common elements are equal,
        // the longer string should be considered "bigger"
        return Integer.compare(len1, len2);
    }
}

Now, just use this custom comparator to sort your strings:

List<String> myList = ...;
Collections.sort(myList, new StringPartsComparator());
like image 79
Mureinik Avatar answered Sep 26 '22 07:09

Mureinik