Home > DeveloperSection > Forums > How to get a highest (last) element in treeset when treeset is sorted with other attribute
Royce Roy
Royce Roy

Total Post:134

Posted on    April-29-2015 12:38 AM

 Java Java  Collection 

 1 Reply(s)
 495  View(s)
Rate this:
I am using a treeset which contains employee class 
TreeSet<Employee> ts = new TreeSet<Employee>(new ComparatorEmpId()); 

Requirements : 

1)My treeset should be sorted by employee Id 
2)(But I want to get the highest salaried employee from treeset (using last) . how do i do that ? 
3)[I tried to use comparator for sorting the employee Id , but for getting a highest salary I should have had the salary attribute sorted ] 

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    April-29-2015 7:19 AM

You can use Collections.max(Collection, Comparator) method for that.

In Java 8 you could also use streams for that:  
This assumes there is method public int getSalary() in Employee class.

Don't want to miss updates? Please click the below button!

Follow MindStick