
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Least Value Element from a Set Using TreeSet in Java
TreeSet is a class of Java Collection Framework that implements the SortedSet Interface.It stores elements in ascending order and does not allow duplicate values therefore, theaccess and retrieval time becomes faster. Because of this excellent feature, TreeSet isfrequently used to store large amounts of information that need to be searched quickly.We will use the Comparable Interface to sort the given TreeSet and then using in-builtmethod named ?first()', we try to get the least value element from that TreeSet.
Java Program to get Least value element from TreeSet
Before jumping into the program, let's familiarize ourselves with a few concepts ?
Comparable Interface
This interface is useful when we want to sort custom objects by their natural ordering. Forexample, It sorts strings in dictionary order and numerics in numerical order. This interfaceis available in ?java.lang' package. Generally, classes and interfaces defined in this packageare by default available for our use therefore, it is not necessary to import this packageexplicitly.
Syntax
class nameOfclass implements Comparable <nameOfclass >
Here, class is the keyword that creates a Class and implements is the keyword that enables the use of features provided by an Interface.
compareTo()
The Comparable interface defines only a single method named ?CompareTo' that can be overridden in order to sort the collection of objects. It gives the power to compare the objects of a class to itself. It returns 0 when ?this' object is equal to passed object, a positive value if ?this' object is greater otherwise a negative value.
Syntax
compareTo(nameOfclass nameOfobject);
first() method
This method is used with an object of TreeSet and does not take any argument. The?first()' method returns the element at position first of the specified TreeSet. Since aTreeSet stores its elements in ascending order, therefore the first element is consideredthe lowest-value element and vice versa the highest.
Syntax
nameOfTreeSetObject.first();
Approach
First, import the ?java.util' package so that we can work with TreeSet
Create a class ?Cart' that implements Comparable Interface. Inside it, declare two variables and define a constructor of this class along with two parameters ?item' and ?price' of type string and integer respectively.
Define ?compareTo' method along with an object of class ?Cart' as a parameter to compare ?this' object with the newly created object.
Now, in the main() method, declare an object named ?trSet' of class ?Cart' of collection type TreeSet and using an in-built method named ?add()' store the details of object to the collection.
In the end, call in-built methods ?last()' and ?first()' to get highest and lowest values respectively.
Example
The following example demonstrates how we can find the least value element from a TreeSet.
import java.util.*; public class Cart implements Comparable <Cart> { String item; int price; Cart(String item, int price) { // constructor // this keyword shows these variables belong to constructor this.item = item; this.price = price; } // overriding method public int compareTo(Cart comp) { if(this.price > comp.price) { // performing comparison return 1; } else { return -1; } } public String toString() { return "Item: " + this.item + ", Price: " + this.price; } public static void main(String[] args) { // Declaring collection TreeSet TreeSet <Cart> trSet = new TreeSet <Cart>(); // Adding object to the collection trSet.add(new Cart("Rice", 59)); trSet.add(new Cart("Milk", 60)); trSet.add(new Cart("Bread", 45)); trSet.add(new Cart("Peanut", 230)); trSet.add(new Cart("Butter", 55)); // to print the objects for (Cart print : trSet) { System.out.println("Item: " + print.item + ", " + "Price: " + print.price); } // calling in-built methods to print required results System.out.println("Element having highest value: " + trSet.last()); System.out.println("Element having lowest value: " + trSet.first()); } }
Output
Item: Bread, Price: 45 Item: Butter, Price: 55 Item: Rice, Price: 59 Item: Milk, Price: 60 Item: Peanut, Price: 230 Element having least value: Item: Bread, Price: 45
Conclusion
We started this article by defining the TreeSet class of Java Collection Framework and inthe next section, we discovered the Comparable interface and a few built-in methods thathelped us in getting the least value element from a Set using Sorting logic on TreeSet.