Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a string based upon value in square bracket

Tags:

java

string

regex

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?

like image 653
anonymous Avatar asked Jan 31 '14 04:01

anonymous


1 Answers

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.

like image 131
ccjmne Avatar answered Oct 13 '22 12:10

ccjmne