×

Java Programs

Java Practice

Java program to get the strictly greater element from TreeSet collection based on a given item

Given a TreeSet collection, we have to get the strictly greater element based on a given item.
Submitted by Nidhi, on June 07, 2022

Problem statement

In this program, we will create a TreeSet collection with integer elements. Then we will get the strictly greater element from the TreeSet collection based on the given item using the higher() method.

Source Code

The source code to get the strictly greater element from the TreeSet collection based on the given item is given below. The given program is compiled and executed successfully.

Example of TreeSet.higher() Method in Java

// Java program to get the strictly greater element 
// from TreeSet collection

import java.io.*;
import java.util.*;

public class Main {
  public static void main(String args[]) {
    TreeSet < Integer > tree = new TreeSet < Integer > ();

    tree.add(30);
    tree.add(20);
    tree.add(25);
    tree.add(10);

    int higher = tree.higher(17);

    System.out.println("Strictly higher element is: " + higher);
  }
}

Output

Strictly higher element is: 20

Explanation

In the above program, we imported the "java.util.*", "java.io.*" packages to use the TreeSet class. Here, we created a public class Main.

The Main class contains a main() method. The main() method is the entry point for the program. And, created a TreeSet collection tree and added integer elements using add() method. Then we get the strictly greater element from the TreeSet collection based on given item 17 using the higher() method and printed the result.

Java TreeSet Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.