// Create a SortedSet of integers SortedSetnumbers = new TreeSet<>(); numbers.add(3); numbers.add(7); numbers.add(2); numbers.add(9); numbers.add(4); // Get the headSet of elements less than 4 SortedSet headSet = numbers.headSet(4); // Print the headSet elements for (int num : headSet) { System.out.print(num + " "); } // Output: 2 3
import java.util.TreeSet; import java.util.SortedSet; public class StringHeadSet { public static void main(String[] args) { // Create a SortedSet of strings SortedSetIn this example, we create a SortedSet of strings and add some fruits to it. We then get the headSet consisting of fruits less than "Grape" and print out the elements. The SortedSet and headSet() method are part of the Java Collections Framework, which is found in the java.util package library.fruits = new TreeSet<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); fruits.add("Grape"); fruits.add("Pear"); // Get the headSet of elements less than "Grape" SortedSet headSet = fruits.headSet("Grape"); // Print the headSet elements for (String fruit : headSet) { System.out.print(fruit + " "); } // Output: Apple Banana } }