first(): This method is available in java.util.TreeSet class of Java.
Syntax:
String java.util.TreeSet.first()
This method returns the first (lowest) element currently in this set.
Parameters: NA
Returns: the first (lowest) element currently in this set.
Throws:
NoSuchElementException - if this set is empty
Approach 1: When no exception
Java
import java.util.TreeSet;public class TreeSetfirst {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.first());}}
Output:
C++
Approach 2: NoSuchElementException
Java
import java.util.TreeSet;public class TreeSetfirst {public static void main(String[] args) {TreeSet<String> treeSet = new TreeSet<String>();System.out.println(treeSet.first());}}
Output:
Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.TreeMap.key(TreeMap.java:1596) at java.base/java.util.TreeMap.firstKey(TreeMap.java:291) at java.base/java.util.TreeSet.first(TreeSet.java:392)
No comments:
Post a Comment