HashSet<String> user = new HashSet<String>(); String SQL = "SELECT distinct userid FROM sch.stutents order by userid ASC"; ResultSet resultSet = connection.createStatement().executeQuery(SQL); while (resultSet.next()) { user.add(resultSet.getString("userid")); } 

If you pull data using pgAdmin III , then correctly sorted data is returned. But when using ResultSet data is clearly not sorted by field!

How to get a sorted result from a database using ResultSet ?

  • How did you determine that the result is not sorted? If you check the user hash table, it does not guarantee the order of the added data. - Pavel Parshin

1 answer 1

HashSet does not guarantee the ordering of elements, since the hashing process itself does not normally spawn sorted sets. If you need sorted sets, then another collection type, such as the TreeSet class, may be a better choice.

TreeSet is a collection that stores its elements in the form of a tree ordered by values. TreeSet encapsulates a TreeMap , which in turn uses a balanced binary red-black tree to store items.

And for reverse sorting in the TreeSet you can use descendingSet() , something like this: user = (TreeSet)user.descendingSet();

  • SQL is correct and pulls data is also true, and the error was just in the hash function! And from what I read, I can conclude that with the help of ResultSet you cannot get sorted data, although in fact it was here and nothing to do with it. I had another case when I had to use LinkedHashSet . - Giovanni
  • one
    @Giovanni ResultSet not and, yes. This class represents the resulting database set. It provides the application with line-by-line access to the results of queries in the database. During the processing of the request, the ResultSet supports a pointer to the current line being processed. The application sequentially moves through the results until they are all processed or ResultSet is closed ... It is important where you store. This could be a set , or maybe a list or a hashmap etc. It's simply important to know what their difference is .... Mozht if you had stored in the list - everything would be right away as planned - Alexey Shimansky