import java.util.TreeSet; import java.util.Iterator; public class TreeSets { public static void main(String[] args) { // Creating a TreeSet TreeSet<String> treeSet = new TreeSet<>(); // Adding elements to the TreeSet treeSet.add("Apple"); treeSet.add("Banana"); treeSet.add("Orange"); treeSet.add("Grapes"); treeSet.add("Mango"); // Trying to add a duplicate element boolean added = treeSet.add("Apple"); boolean removed = treeSet.remove("Banana"); System.out.println("Element 'Banana' removed from the TreeSet."); // Checking if an element exists in the TreeSet boolean contains = treeSet.contains("Orange"); System.out.println("TreeSet contains 'Orange': " + contains); // Iterating over the elements in the TreeSet using an Iterator System.out.println("Iterating over TreeSet elements using Iterator:"); Iterator<String> iterator = treeSet.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } // Getting the first and last elements System.out.println("First element: " + treeSet.first()); System.out.println("Last element: " + treeSet.last()); // Clearing the TreeSet treeSet.clear(); System.out.println("TreeSet cleared. Current size: " + treeSet.size()); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter