1

I have some codes looking like the one of following:

  • aaa_bbb_d2_aa
    aaa_bbb_d3_aa
    aaa_bbb_d11_aa

  • eee_b2b_c2_ac

In general they should be sorted as strings, however in case of “aaa_bbb_d3_aa” vs. “aaa_bbb_d11_aa” the former should come first in contrast to simple string sorting.

The numerical part that is important for sorting always resides after either the “_d” or “_c” substring and always is followed by “_aa” or by “_ac” ending the string.

What is an efficient sorting algorithm in Java or SQL?

Laurentiu L.
  • 6,566
  • 1
  • 34
  • 60
Alex
  • 7,007
  • 18
  • 69
  • 114

2 Answers2

1
Collections.sort(yourListOfString, (String a, String b) ->
{
    int comparison = Integer.valueOf(a.split("_")[2].replaceAll("[dc]", "")).compareTo(Integer.parseInt(b.split("_")[2].replaceAll("[dc]", "")));

    return comparison == 0
             ? a.split("_")[3].compareTo(b.split("_")[3])
             : comparison;
});

(I assume all your strings are in a list)

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
0

I ended up with NaturalOrderComparator.java: https://github.com/paour/natorder . Thanks @dasblinkenlight for the useful comment

Alex
  • 7,007
  • 18
  • 69
  • 114