---
title: "How to get a highest (last) element in treeset when treeset is sorted with other attribute"  
description: "How to get a highest (last) element in treeset when treeset is sorted with other attribute"  
author: "Royce Roy"  
published: 2015-04-29  
updated: 2015-04-29  
canonical: https://www.mindstick.com/forum/23158/how-to-get-a-highest-last-element-in-treeset-when-treeset-is-sorted-with-other-attribute  
category: "java"  
tags: ["java", "collection"]  
reading_time: 1 minute  

---

# How to get a highest (last) element in treeset when treeset is sorted with other attribute

I am using a treeset which contains [employee](https://www.mindstick.com/articles/85431/remote-employee-training-tips-tricks) [class](https://www.mindstick.com/blog/165/generic-class-in-c-sharp)

```
TreeSet<Employee> ts = new TreeSet<Employee>(new ComparatorEmpId()); 
```

\
[Requirements](https://www.mindstick.com/articles/12850/drivers-license-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](https://www.mindstick.com/articles/1581/sorting-list-with-side-bar) the employee Id , but for getting a [highest salary](https://www.mindstick.com/forum/33705/find-nth-highest-salary-in-sql-serever) I should have had the salary [attribute](https://www.mindstick.com/blog/221/attributes-reflection) sorted ] \

## Replies

### Reply by Anonymous User

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. \


---

Original Source: https://www.mindstick.com/forum/23158/how-to-get-a-highest-last-element-in-treeset-when-treeset-is-sorted-with-other-attribute

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
