Suggested algorithm
You could simply:
- split your
String
on each new timestamp, then
- sort the resulting array and finally
- 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.