Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting with Treeset

 
RaviSingh Kumar
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have an employee object having fields as employee first name,last name, employee Id , salary, designation .

I have to store it in treeset. But when i want to retrive it , it must be sorted according to employee id.

The problem is that i am unable to sort it according to employee id.(But able to sort according to first name, last name etc using comparable interface).

Please let me now how to do it.

Thanks in advance
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
to sort an object use Comparator or Comparable interfaces .to know more search in google
 
RaviSingh Kumar
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have used the comparable interface. But when i implement the compareTo method i am unable to sort on the basis of employee id since it is integer.

But i am able to sort on the basis of first name, last name etc.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48968
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why have you used Comparable? Its documentation says it implies a "natural ordering" which you don't have for employees. You have several possible orderings, eg by name, seniority, salary, ID number, all of which might be valid. Not one "natural" ordering.

So you want to pass a Comparator<Employee> which simply works out the difference between the ID numbers. If they are ordinary positive ints you can simply subtract the IDs to get a result.
 
Rob Spoor
Sheriff
Pie
Posts: 20531
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:If they are ordinary positive ints you can simply subtract the IDs to get a result.

And if they are not the following works always:
 
Brijesh Verma
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
do one thing put all Employee object in list object and

call this methos Collections.sort(listObject); in that class where you want sorting

put this in Employee class

public int compareTo(Object o) {
Employee e = (Employee ) o;
return this.id.compareToIgnoreCase(e.getId());

}

 
Campbell Ritchie
Sheriff
Pie
Posts: 48968
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the id field is an int, that last code will fail to compile. As I said: not Comparable<Employee> but one or more Comparator<Employee> objects.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic