Home  >  Article  >  Java  >  Use the sorting logic of TreeSet in Java to get the maximum and minimum elements in the set

Use the sorting logic of TreeSet in Java to get the maximum and minimum elements in the set

WBOY
WBOYforward
2023-09-02 12:33:071024browse

Use the sorting logic of TreeSet in Java to get the maximum and minimum elements in the set

TreeSet is a class in the Java Collection Framework that implements the SortedSet interface. It stores elements in ascending order and does not allow duplicate values, so access and retrieval times become faster. Because of this excellent functionality, TreeSets are often used to store large amounts of information that need to be searched quickly. We will use the Comparable interface to sort a given TreeSet and then, using built-in methods, try to get the highest and lowest value elements from that TreeSet.

Java program to get the highest and lowest value elements from a TreeSet

Before entering the program, let us first familiarize ourselves with some concepts

Similar interface

This interface is useful when we want to sort custom objects in their natural order. For example, it sorts strings lexicographically and numbers numerically. This interface is available in the "java.lang" package. Generally speaking, the classes and interfaces defined in this package are available to us by default, so there is no need to import this package explicitly.

grammar

class nameOfclass implements Comparable<nameOfclass>

Here, class is the keyword to create a class, and implements is the keyword that allows the use of the functions provided by the interface.

compareTo()

The Comparable interface only defines a method called "CompareTo" which can be overridden to sort a collection of objects. It provides the ability to compare objects of a class with itself. Returns 0 when the "this" object is equal to the passed object, a positive value if the "this" object is greater, and a negative value otherwise.

grammar

compareTo(nameOfclass nameOfobject);

last() and first() methods

Both methods are used with TreeSet objects and take no parameters. The ‘last()’ method returns the end element of the specified TreeSet, and the ‘first()’ method returns the element at the first position. Since a TreeSet stores its elements in ascending order, the last element is considered as the highest value element and vice versa as the lowest value element.

method

  • First, import the "java.util" package so that we can use TreeSet

  • Create a class "Cart" that implements Comparable Interface. In it declare two variables and define the constructor of the class and the two parameters "item" and "price" of type string and integer respectively.

  • Define the "compareTo" method along with an object of the "Cart" class as a parameter to compare the "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 add the details of the object using the inbuilt method named "add()" Store to collection.

  • Finally, call the built-in methods "last()" and "first()" to obtain the highest and lowest values ​​respectively.

Example

The following example demonstrates how to find the 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

in conclusion

We first defined the TreeSet class of the Java Collection Framework. In the next section, we discovered the Comparable interface and some built-in methods that help us use the sorting logic on the TreeSet to get the highest and lowest value elements from the Set.

The above is the detailed content of Use the sorting logic of TreeSet in Java to get the maximum and minimum elements in the set. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete