aspose file tools*
The moose likes Beginning Java and the fly likes sorting  a hashset based on its value Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "sorting  a hashset based on its value " Watch "sorting  a hashset based on its value " New topic
Author

sorting a hashset based on its value

kalai sundar
Ranch Hand

Joined: May 25, 2005
Posts: 69
Could not sort a hashset based on its value . In the below code i have hashset
which contains multiple student information .So want to sort the haset based on the student id.
Below code is not working.Can anyone help me.

Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

HashSets have no notion of order. You are sorting an ArrayList anonymous instance. This won't affect the HashMap.

(next time, UseCodeTags when you post some code)


[My Blog]
All roads lead to JavaRanch
Dinakar Kas
Ranch Hand

Joined: Jul 11, 2010
Posts: 34
Use TreeSet and supply the Comparator argument to its constructor. I will solve your problem.

Dinakar
Dinakar Kas
Ranch Hand

Joined: Jul 11, 2010
Posts: 34
sorry. *It* will solve yor problem.
kalai sundar
Ranch Hand

Joined: May 25, 2005
Posts: 69
I am not suppose to change its as Treeset .I have to sort the student information
inside the HashSet based on student id.
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

kalai sundar wrote:I am not suppose to change its as Treeset .I have to sort the student information
inside the HashSet based on student id.

You can't. You might have misunderstood the requirements of your assignment.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11231
    
  16

The whole point of a hashset is to make it easy/quick to find/insert something. You pass it a key, and a hash value is computed. This is used to determine where to store the actual data.

If you then sort the values inside the hashset, that would move where stuff is. That then means you can't easily find it.

It's kind of like saying "i'm going to put stuff into a sorted list, then randomize it". if you do that, you no longer have a sorted list. If you re-arrange stuff in the hashset, it is no longer a hashset.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
 
subject: sorting a hashset based on its value