Search code examples
javalistjdbctop-n

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
... ...

Solution

  • 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.