Java: Find the numbers less than 7 in a tree set
Java Collection, TreeSet Exercises: Exercise-9 with Solution
Write a Java program to find numbers less than 7 in a tree set.
Sample Solution:
Java Code:
import java.util.TreeSet;
import java.util.Iterator;
public class Exercise9 {
public static void main(String[] args) {
// creating TreeSet
TreeSet <Integer>tree_num = new TreeSet<Integer>();
TreeSet <Integer>treeheadset = new TreeSet<Integer>();
// Add numbers in the tree
tree_num.add(1);
tree_num.add(2);
tree_num.add(3);
tree_num.add(5);
tree_num.add(6);
tree_num.add(7);
tree_num.add(8);
tree_num.add(9);
tree_num.add(10);
// Find numbers less than 7
treeheadset = (TreeSet)tree_num.headSet(7);
// create an iterator
Iterator iterator;
iterator = treeheadset.iterator();
//Displaying the tree set data
System.out.println("Tree set data: ");
while (iterator.hasNext()){
System.out.println(iterator.next() + " ");
}
}
}
Sample Output:
Note: Exercise9.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. Tree set data: 1 2 3 5 6
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Compare two tree sets.
Next: Get the element in a tree set which is greater than or equal to the given element.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/collection/java-collection-tree-set-exercise-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics