Getting Highest and Lowest Value Element From a Set by using Sorting Logic on 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-builtmethods, we try to get the highest and lowest value elements from that TreeSet.

Java Program to get Highest and Lowest value elements 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. For example, It sorts strings in dictionary order and numerics in numerical order. This interface is available in ‘java.lang’ package. Generally, classes and interfaces defined in this package are by default available for our use therefore, it is not necessary to import this package explicitly.

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);

last() and first() method

Both methods are used with an object of TreeSet and do not take any argument. The ‘last()’ method returns the ending element of specified TreeSet and the ‘first()’ method returns the element at position first. Since a TreeSet stores its elements in ascending order, therefore the last element is considered the highest-value element and vice versa the lowest.

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 highest and lowest value elements 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 highest value: Item: Peanut, Price: 230
Element having lowest 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 highest and lowest value elements from a Set using Sorting logicon TreeSet.

Updated on: 20-Jul-2023

42 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements