Best way to sort bracketed values in a string both alphabetically and by number?

 

问题

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?

解答

将每行字符串按对应的数据类型拆分后排序。用Java 实现代码较长。

Java 下的开源包 SPL 很容易写,只要2句:


A

1

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

2

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

SPL 提供了 JDBC 供 Java 调用,把上面的脚本存为sort.splx,在 Java 中以存储过程的方式调用脚本文件:

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

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

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

SPL 源代码:https://github.com/SPLWare/esProc

问答搜集