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?
You could simply:
String
on each new timestamp, thenUsing 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());
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With