• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

sorting a hashset based on its value

 
kalai sundar
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Dinakar Kas
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use TreeSet and supply the Comparator argument to its constructor. I will solve your problem.

Dinakar
 
Dinakar Kas
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry. *It* will solve yor problem.
 
kalai sundar
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 12098
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic