Home > database >  String sorting with dots in java
String sorting with dots in java

Time:08-24

I can not type cast to Double due nature of data(multile dots ex: 1.2.1)

How to sort in java?

List<String> arr= new ArrayList<>();
arr.add("1.1");
arr.add("10.1");
arr.add("1.2.1");
arr.add("2.0");
arr.add("11.2");
arr.add("2.2.1");

the expected outcome is

1.1
2.0
2.2.1
10.1
11.2

CodePudding user response:

Example for a Comparator:

Comparator<String> indexComparator = (index1, index2) -> {
    int[] parts1 = Stream.of(index1.split("\\.")).mapToInt(Integer::parseInt).toArray();
    int[] parts2 = Stream.of(index2.split("\\.")).mapToInt(Integer::parseInt).toArray();
    
    // from Java 9 on: return Arrays.compare(parts1, parts2);
    // in Java 8:
    int n = Math.min(parts1.length, parts2.length);
    for (int i = 0; i < n; i  ) {
        if (parts1[i] < parts2[i]) return -1;
        if (parts1[i] > parts2[i]) return 1;
    }
    return Integer.compare(parts1.length, parts2.length);
};

Sort using this Comparator:

Collections.sort(arr, indexComparator);

EDIT: Added the Java 9 solution, Holger thankfully pointed out.

CodePudding user response:

  1. Introduce a class that represents the data you're sorting (e.g. class SemVer), with a static from(String) method that will parse the string and return an instance of SemVer.
  2. Introduce a Comparator that describes the logic for comparing two instances of SemVer.
  3. Use the comparator as an argument to Collections.sort().
  • Related