Write a Java program to find the numbers less than n in a tree set.
Java TreeSet class implements the Set interface that uses a tree for
storage. It inherits AbstractSet class and implements the NavigableSet
interface. The objects of the TreeSet class are stored in ascending
order. And as it is a set, the elements in a treeset are unique - no duplicates.
The difference between a hashset and treeset is that, in hashset the elements are not in any order but in a treeset they are in descending order.
Once we create a TreeSet, you can add elements to it using add() method.
To iterate over the elements of a TreeSet, you can use an iterator interface or you can use a for each loop. But if you just want to print the elements, you can give the treeset object as a parameter to println() method.
Numbers less than n :
To obtain elements which are less than a given key, you can use the method headSet(). This method returns a SortedSet with values which are strictly less than the given value.
So now we are ready to write the program.
We created a TreeSet and added n elements to it. Now if we print the set usingTreeSet<Integer> set = new TreeSet<>();for(int i=0;i<5;i++){int num = scanner.nextInt();set.add(i*i);}
System.out.println(set) we get
[0,1,4,9,16]
And
Finally to get the subset with all elements smaller than n, we use
SortedSet subset = set.headSet(n);
Here is our complete program.
import java.util.Scanner; import java.util.SortedSet; import java.util.TreeSet; public class TreeSetDemo { public TreeSet<Integer> createSet(int n){ TreeSet<Integer> set = new TreeSet<>(); Scanner scanner = new Scanner(System.in); for(int i=0;i<n;i++){ int num = scanner.nextInt(); set.add(num); } return set; } public static void main(String args[]){ TreeSetDemo obj = new TreeSetDemo(); TreeSet<Integer> s1 = obj.createSet(5); System.out.println("Enter n:"); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); SortedSet<Integer> subset = s1.headSet(n); System.out.println("The elements smaller than "+n+" are"+subset); } }
Comments
Post a Comment