Selecting top n elements elements in java list of models with criteria
题
I have a MySQL table as such
id_user id_info
1 45
1 54
1 12
2 16
2 48
3 94
... ...
For all of my users, I want to select n info at random (say, 1), or with a criteria. I know that it is quite intensive in pure MySQL when the table is large (I tried this solution http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/)
In Java, I query for the whole table, and puts the data in a List<ModelData>
, where ModelData
is the straightforward model, with only getters and setters. What would be the best way to strip this list so at the end I would have :
id_user id_info
1 54
2 16
3 94
... ...
解决方案
If you want Sorted record I would prefer go for TreeMap.
Map<Integer,id_info_type> records =new TreeMap<Integer, id_info_type>()
Key : Integer
Value : id_info_type if it is String go for String.
I think that might help you.
No need to care about duplicates that will be taken care by you Map.
其他提示
Instead of a list , put them in a hashmap with the userid as key.
I would suggest you do your operation while you create your List
as follows
- Use a
LinkedHashMap
and use user_id as key and info_id as value. - While you iterate over your rows, check if your
LinkedHashMap
contains that key, if false insert the info_id as value. If that key already exists randomly change the value with new one (use a random number decision with 0.5 possibility).
Finally you will end up with what you asked hopefully.