How to sort this string and rebuild the same sorted string again

advertisements

How can I sort values in this string based on the integral parts i.e.

Input:

[160,190];[650,790];[901,974];[401,540];[60,90];

O/p:

[60,90];[160,190];[401,540];[650,790];[901,974];

Obviously a regular sort must do in this case but I am not sure about where should I trim the strings compare and rebuild the exact string with optimized approach.


If each [] specifies a unique range of values, you can extract all numbers, sort them and then construct the resultant string back by grouping two elements in each [].

Pattern pattern = Pattern.compile("(\\d+)");
Matcher matcher = pattern.matcher(s);
Set<Integer> numbers = new TreeSet<>();

while(matcher.find()) {
    numbers.add(Integer.parseInt(matcher.group(1)));
}

Next step would be to iterate over numbers and use the current and next index to form the resultant string.

An even better approach is to split the string on ; and use @Sergey N Lukin's Comparator to sort the values

    String s = "[160,190];[650,790];[901,974];[401,540];[60,90];";
    String[] values = s.split(";");
    Set<String> sortedValues = new TreeSet<>(new TokensComparator());
    sortedValues.addAll(Arrays.asList(values));

Eventually, join the set's elements with a semi-colon(;) using a loop or Google Guava's Joiner

Joiner.on(';').join(sortedValues);