Best Way to Sort Bracketed Values in a String Both Alphabetically and by Number
Question
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.
SPL Official Website 👉 https://www.scudata.com
SPL Feedback and Help 👉 https://www.reddit.com/r/esProc_SPL
SPL Learning Material 👉 https://c.scudata.com
SPL Source Code and Package 👉 https://github.com/SPLWare/esProc
Discord 👉 https://discord.gg/cFTcUNs7
Youtube 👉 https://www.youtube.com/@esProc_SPL
Chinese version