search
HomeJavajavaTutorialUse 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

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. If there is any infringement, please contact admin@php.cn delete
How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

How does platform independence simplify deployment of Java applications?How does platform independence simplify deployment of Java applications?May 02, 2025 am 12:15 AM

Java'splatformindependenceallowsapplicationstorunonanyoperatingsystemwithaJVM.1)Singlecodebase:writeandcompileonceforallplatforms.2)Easyupdates:updatebytecodeforsimultaneousdeployment.3)Testingefficiency:testononeplatformforuniversalbehavior.4)Scalab

How has Java's platform independence evolved over time?How has Java's platform independence evolved over time?May 02, 2025 am 12:12 AM

Java's platform independence is continuously enhanced through technologies such as JVM, JIT compilation, standardization, generics, lambda expressions and ProjectPanama. Since the 1990s, Java has evolved from basic JVM to high-performance modern JVM, ensuring consistency and efficiency of code across different platforms.

What are some strategies for mitigating platform-specific issues in Java applications?What are some strategies for mitigating platform-specific issues in Java applications?May 01, 2025 am 12:20 AM

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

What is the relationship between Java's platform independence and microservices architecture?What is the relationship between Java's platform independence and microservices architecture?May 01, 2025 am 12:16 AM

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

How does GraalVM relate to Java's platform independence goals?How does GraalVM relate to Java's platform independence goals?May 01, 2025 am 12:14 AM

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor