In order to get the value element of the user-defined object, one needs to implement the sorting logic in TreeSet. Now in order to implement the sorting logic on the user-defined objects, the Comparator object needs to be passed along the TreeSet constructor call. Further, Comparator implementation will hold the sorting logic. For this, the compare() method needs to be overridden to provide sorting logic on user-defined objects. Lastly, the least element is extracted out using the first() method.
Input : Set: ["A"=36678 , "B"=456456 ,"C"=76434 ,"D"=4564] Output: Least value => element: D, value: 4564 Input : Set: ["x"=1, "y"=2 ,"z"=3] Output: Set: Least value =>element: x, value: 1
To get the least value element TreeSet
- Use comparators to order the object of a user-defined class.
- Implementing the sorting functionality that overrides the compare() method to sort the TreeSet by value.
- After sorting, the first object of the TreeSet will be the least value element.
Least value =>element: D, value: 4564
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.