简体   繁体   English

最好使用TreeMap还是按顺序排序?

[英]Better to use TreeMap or order by?

What would be better programing practice? 什么是更好的编程实践?

Is it better to use order by clause in sql or put the results in treemap vs hashmap in java for things like drop down? 在sql中使用order by子句或者将结果放在java中的treemap vs hashmap中是否更好?

If you are thinking about performance, then big resultsets are better sorted at the database end, especially when the columns you are sorting on are indexed. 如果您正在考虑性能,那么在数据库端更好地对大结果集进行排序,尤其是在对要排序的列进行索引时。

For smaller data-sets performance difference might not be significant, but I think SQL's Order By clause will be the simpler approach in most cases. 对于较小的数据集,性能差异可能不大,但我认为SQL的Order By子句在大多数情况下将是更简单的方法。

By the way you will still have to use LinkedHashMap instead of plain HashMap if you must store the already sorted data in a map before using it. 顺便说一下,如果必须在使用之前将已经排序的数据存储在地图中,您仍然必须使用LinkedHashMap而不是普通的HashMap。 Because LinkedHashMap will keep the data in insertion order while HashMap won't. 因为LinkedHashMap将保持数据的插入顺序,而HashMap则不会。

If you want the data to be automatically sorted as it is put into the Map then you will need TreeMap or another sorted map implementation. 如果您希望数据在放入Map时自动排序,那么您将需要TreeMap或其他有序映射实现。

A lot depends on the implementation, list size, etc. I would say if you can do an order by in your sql query, that would push the overhead to the database, and you wouldn't have to do the sort in the application. 很大程度上取决于实现,列表大小等。我会说如果你可以在你的sql查询中执行一个命令,这会将开销推到数据库,你不必在应用程序中进行排序。 Also make sure the datastructure you use in your application preserves the order, ie don't insert the results into a hashmap. 还要确保在应用程序中使用的数据结构保留顺序,即不将结果插入到散列映射中。 But a lot depends on the specifics of what you are trying to achieve. 但很大程度上取决于你想要达到的目标的细节。

Also depends on the fields you are trying to do "order by" or using it to sort at will in the Java code. 还取决于您尝试“按顺序”执行的字段,或者使用它在Java代码中随意排序。 But I would depend on the DB doing the order by in most cases. 但在大多数情况下,我会依赖数据库执行命令。

First off.. 首先..

Using HashMap would destroy any attempt to 'order by' in your SQL since you are not guaranteed to get back the order you put the items. 使用HashMap会破坏您在SQL中“排序”的任何尝试,因为您无法保证取回您放置项目的顺序。 So if you used an 'order by' in your SQL you would be forced to use a LinkedHashMap for storage to retain item order. 因此,如果您在SQL中使用“order by”,则会被迫使用LinkedHashMap进行存储以保留项目顺序。

A TreeMap would order for you, if you set up a valid comparator. 如果您设置了有效的比较器,TreeMap将为您订购。

My preference would be based on the size of the lists and usage. 我的偏好将基于列表的大小和用法。 If many people will be accessing this list on a daily basis and refreshing it, I would prefer to have their own user interfaces handle the ordering.. This part really depends. 如果很多人每天都会访问这个列表并刷新它,我宁愿让他们自己的用户界面处理订单..这部分真的取决于。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM