TreeSet last() in Java

last(): This method is available in java.util.TreeSet class of Java.

Syntax:

K java.util.TreeSet.last()

This method returns the last (highest) element currently in this set.

Parameters: NA

Returns: the last (highest) element currently in this set.

Throws:

NoSuchElementException - if this set is empty

Approach 1: When no exception

Java

import java.util.TreeSet;

public class TreeSetlast {
    public static void main(String[] args) {

        TreeSet<String> treeSet = new TreeSet<String>();

        treeSet.add("Hello");
        treeSet.add("Java");
        treeSet.add("Program");
        treeSet.add("C++");

        System.out.println(treeSet.last());

    }
}

Output:

Program


Approach 2: NoSuchElementException

Java

import java.util.TreeSet;

public class TreeSetlast {
    public static void main(String[] args) {

        TreeSet<String> treeSet = new TreeSet<String>();

        System.out.println(treeSet.last());

    }
}

Output:

Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.TreeMap.key(TreeMap.java:1596) at java.base/java.util.TreeMap.lastKey(TreeMap.java:298) at java.base/java.util.TreeSet.last(TreeSet.java:399)


No comments:

Post a Comment