5

I have a string eg:

[01:07]bbbbbbb[00:48]aaaaaa[01:36]ccccccccc[03:45]gggggggg[03:31]fffffff[01:54]ddddddddd[02:09]eeeeeee[03:59]hhhhhhhh

this needs to be Sorted as

[00:48]aaaaaa[01:07]bbbbbbb[01:36]ccccccccc[01:54]ddddddddd[02:09]eeeeeee[03:31]fffffff[03:45]gggggggg[03:59]hhhhhhhh  

which is based upon the string inside the square bracket.
how can i do this in java?

ccjmne
  • 9,333
  • 3
  • 47
  • 62
anonymous
  • 483
  • 2
  • 8
  • 24

1 Answers1

10

Suggested algorithm

You could simply:

  1. split your String on each new timestamp, then
  2. sort the resulting array and finally
  3. concatenate its ordered content.

Actual code sample

Using the Stream library introduced in Java 8, it can be done in within a single expression:

final String sorted = Arrays.asList(input.split("(?=\\[)")).stream().sorted().collect(Collectors.joining());

Original answer pre-Java 8

final String input = "[01:07]bbbbbbb[00:48]aaaaaa[01:36]ccccccccc[03:45]gggggggg[03:31]fffffff[01:54]ddddddddd[02:09]eeeeeee[03:59]hhhhhhhh";
final String entries[] = input.split("(?=\\[)");
Arrays.sort(entries);

String res = "";
for (final String entry : entries) {
    res += entry;
}

System.out.println(res);

Output:

[00:48]aaaaaa[01:07]bbbbbbb[01:36]ccccccccc[01:54]ddddddddd[02:09]eeeeeee[03:31]fffffff[03:45]gggggggg[03:59]hhhhhhhh

Follow-up question in the comments section

why do I do input.split("(?=\\[)")?

String#split works with a Regular Expression but [ (and ]) are not standard characters, "regex-wise". So, they need to be escaped — using \[ (and \]).

However, in a Java String, \ is not a standard character either, and needs to be escaped as well.

See this answer on Stack Overflow for more details.

ccjmne
  • 9,333
  • 3
  • 47
  • 62
  • @ccjmne can you please explain input.split("\\["), I am aware of the split method but never seen this kind of splitting. Lil bit elaboration would be really appreciated. – Nick Div Jan 31 '14 at 05:46
  • @kapilchhattani Sure, you're right, I should/could have explained this. I just added that explanation to my answer. Thank you for pointing that out! – ccjmne Jan 31 '14 at 05:55