Reputation: 5018
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?
Upvotes: 4
Views: 855
Reputation: 6091
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. So if you used an 'order by' in your SQL you would be forced to use a LinkedHashMap for storage to retain item order.
A TreeMap would order for you, if you set up a valid comparator.
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.
Upvotes: 0
Reputation: 11625
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.
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. Because LinkedHashMap will keep the data in insertion order while HashMap won't.
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.
Upvotes: 3
Reputation: 547
Also depends on the fields you are trying to do "order by" or using it to sort at will in the Java code. But I would depend on the DB doing the order by in most cases.
Upvotes: 0
Reputation: 5006
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. Also make sure the datastructure you use in your application preserves the order, i.e. don't insert the results into a hashmap. But a lot depends on the specifics of what you are trying to achieve.
Upvotes: 0