Best Way to Sort Bracketed Values in a String Both Alphabetically and by Number

Question

Source:https://stackoverflow.com/questions/69932118/best-way-to-sort-bracketed-values-in-a-string-both-alphabetically-and-by-number


Don't worry about the actual data here. It's garbage. The ultimate structure is $ with a series of brackets where sometimes the value in between the brackets is an alphabetic string and sometimes it is a number.

I need to sort those ArrayList items in order, where if the node in between the brackets is in quotes it is sorted alphabetically, but if it is outside quotes, it should be sorted as a number. i.e. the order should be:

"$['book'][0]['title']"

"$['book'][1]['title']"

"$['book'][2]['title']"

"$['book'][10]['title']"

"$['movie']['series'][0]['title']"

"$['movie']['series'][1]['title']"

"$['movie']['series'][2]['title']"

"$['movie']['series'][10]['title']"

not:

"$['book'][0]['title']"

"$['book'][1]['title']"

"$['book'][10]['title']"

"$['book'][2]['title']"

"$['movie']['series'][0]['title']"

"$['movie']['series'][1]['title']"

"$['movie']['series'][10]['title']"

"$['movie']['series'][2]['title']"

I expect I need to implement a custom Comparator for this, but I'm having trouble coming up with the most efficient way to parse these strings and do the sorting. Does anyone have a suggested approach for this?

Answer

To split each row of string according to its data type and sort it, the Java code will be lengthy.

Suggest you using SPL, an open-source Java package, to do it. Two lines of code are enough:

A

1

=file("data.txt").read@n()

2

=A1(A1.(mid(~,4,len(~)-5).split@p("][")).psort())

SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as sort.splx and invoke it in a Java application as you call a stored procedure:

Class.forName("com.esproc.jdbc.InternalDriver");

con= DriverManager.getConnection("jdbc:esproc:local://");

st = con.prepareCall("call sort()");
st.execute();

View SPL source code.