开发者

How can I sort ResultSet in java?

开发者 https://www.devze.com 2023-01-29 13:00 出处:网络
I can\'t do ORDER BY in 开发者_Go百科the db by the wayExtract the results into a List<YourResultType> and use Collections.sort(). If you only ever need to sort in one \"natural\" order, then imp

I can't do ORDER BY in 开发者_Go百科the db by the way


Extract the results into a List<YourResultType> and use Collections.sort(). If you only ever need to sort in one "natural" order, then implement Comparable<T> in the result type itself... otherwise implement Comparator<T> once per sort order, and pass an instance of the relevant comparator to Collections.sort().


You do ORDER BY in the DB.

You should reassess why you can't do this. If someone asked "how do I insert a screw with a hammer? I can't use a screwdriver by the way", it would be irresponsible not to persuade them that the screwdriver was the right solution in the first instance.

If you really, really can't order the result set natively, you're out of luck. It's just a stream from the database, so you'd have to read it all into a temporary List, sort that collection and then go from there. For small result sets this isn't likely to be a problem, but for large ones this will likely impose quite a hit on efficiency.


Move the data out of the ResultSet into whatever object representation you want and then sort the data just as you would any other data at that point.

If you make use of Collections.Sort to perform your sorting on a complex object you will need to implement Comparator.


It is possible to sort it in the database before you run the query and then store in resultSet.

SELECT * FROM tableName ORDER BY columnName ASC

Is something like this that you want?


It looks like you would have to be responsible for implementing the ResultSet interface with a custom object that would give you the functionality you're looking for....sorry.


This can be solved in the query itself. You order by a calculated column. Your calculated column converts the natural value to a value that can be sorted numerically or alphabetically. You might define a "convert" function and call that function in the order by clause.

At some level the natural to numeric conversion must happen whether in your code or in the database. An algorithm is an algorithm no matter where it runs.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号