Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Collection, TreeSet Exercises: Find the numbers less than 7 in a tree set

Java Collection, TreeSet Exercises: Exercise-9 with Solution

Write a Java program to find the 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:

Flowchart: Find the numbers less than 7 in a tree set

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.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe