HOW TO GET A HIGHEST (LAST) ELEMENT IN TREESET WHEN TREESET IS SORTED WITH OTHER ATTRIBUTE

Royce Roy

Total Post:149

Points:1043
Posted by  Royce Roy
 801  View(s)
Ratings:
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 ] 

  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: How to get a highest (last) element in treeset when treeset is sorted with other attribute

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

    In Java 8 you could also use streams for that:  

    ts.stream().max(Comparator.comparingInt(Employee::getSalary)).get()
    This assumes there is method public int getSalary() in Employee class.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!