How to sort numbers with leading zeros in Java?

Hi I have a list of strings 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 the "-" and leading zeros, but then 0-1 -> 1 and 1 -> 1 match and cannot be sorted. Another thing that comes to my mind is to remove the zero in these numbers, which do not lead to zero, to put 0 behind, therefore

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

then use java sort and return numbers in starting position, but sorted?

Edit:

  • The structure is unlimited in depth, therefore 1-2-3-4-5-6 ...
  • I can only have one lead 0
  • Only dashes (-) and periods (.) Are allowed decimeters.
+7
java sorting algorithm
source share
1 answer

I would split the string by the - character, and then convert each part to 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 the rows:

 List<String> myList = ...; Collections.sort(myList, new StringPartsComparator()); 
+8
source share

All Articles