×

Java Programs

Java Practice

Java program to get and remove the largest element from the TreeSet collection

Given a TreeSet collection, we have to get and remove the largest element.
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 and remove the largest element from the TreeSet collection using the pollLast() method. The pollLast() method returns null, if the TreeSet is empty.

Source Code

The source code to get and remove the largest element from the TreeSet collection is given below. The given program is compiled and executed successfully.

Example of TreeSet.pollLast() Method in Java

// Java program to get and remove the largest 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);

    System.out.println("TreeSet: " + tree);

    int item = tree.pollLast();

    System.out.println("Removed item is: " + item);
    System.out.println("TreeSet: " + tree);
  }
}

Output

TreeSet: [10, 20, 25, 30]
Removed item is: 30
TreeSet: [10, 20, 25]

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 and removed the largest element from the TreeSet collection using the pollLast() method and printed the updated TreeSet.

Java TreeSet Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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