Getting Highest and Lowest Value Element From a Set by Using Sorting Logic on TreeSet in Java
TreeSet in java implements the Set Interface and uses a red-black tree for storing values. We use TreeSet for sorting as the elements in TreeSet are stored in ascending order by default. Once the TreeSet is created, we can get the Highest Element Value from the Last element of the TreeSet and the first element value from the first element of TreeSet. We have to pass the Comparator objects along with the TreeSet declaration first. Now, we can simply do this by Creating a TreeSet and adding elements and then sorting the elements by a certain attribute, finally getting the Highest element by last() and lowest by first() functions on TreeSet. We will have to Override the compare method for implementing the Sorting. The TreeSet Declaration would follow the Syntax given below :
TreeSet<Comparator> name = new TreeSet<Comparator>(new ComparatorClass());
- name: Name of the TreeSet Created
- Comparator: Comparator Object
- ComparatorClass(): Class used for implementing Sorting Function(compare method)
Returns: TreeSet where we can add values
For example, we want to create a TreeSet having names and Age of a group, and we want to find the Person with the highest Age and Value and with the lowest Age and Value
Input : Name - "Ramesh" Age - 20 Name - "Suresh" Age - 48 Name - "Ankit" Age - 14 Name - "Madhav" Age - 78 Output : Highest Age Person: Name : Madhav-- Age : 78 Lowest Age Person: Name : Ankit-- Age : 14
Input : Name - "Ramesh" Age - 20 Name - "Suresh" Age - 20 Name - "Ankit" Age - 78 Name - "Madhav" Age - 78 Output : Highest Age Person: Name : Ankit-- Age : 78 Lowest Age Person: Name : Suresh-- Age : 14
For example1 all the ages are distinct so highest and lowest are found based on age value.
For example2 highest age values are the same so the person name at last() of treeset is given the highest value i.e ‘A’ < ‘M’ so Ankit has the highest age whereas if the lowest age values are the same name at first() of treeset is given lowest value i.e ‘S’ > ‘R’ so Suresh has the lowest age.
Highest Age Person: Name: Ankit-- age: 78 Lowest Age Person: Name: Suresh-- age: 20