In: Computer Science
The following program can be done all in the main method. It demonstrates that a TreeSet eliminates duplicates and is ordered.
Create a Random object with a seed of 5.
Create an ArrayList numAL of type Integer
Populate numAL with 10 numbers randomly selected from 0 to 6
Print out numAL
Create a TreeSet numTS of type Integer
Create an Iterator alIter from numAl and use it to add all the elements of numAL in numTS.
Print out numTS
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import java.util.TreeSet;
public class TestTreeSet {
public static void main(String[] args) {
// creating random object
Random rand = new Random(5);
// creating arraylist
ArrayList<Integer> numAL = new ArrayList<>();
// generating 10 random numbers and adding
for (int i = 0; i < 10; i++)
numAL.add(rand.nextInt(7));
// printing arraylist
System.out.println(numAL);
// creating TreeSet
TreeSet<Integer> numTS = new TreeSet<>();
// creating iterator
Iterator<Integer> itr = numAL.iterator();
// iterating through arraylist and adding elements to TreeSet
while (itr.hasNext())
numTS.add(itr.next());
// printing TreeSet
System.out.println(numTS);
}
}
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
I AM HERE TO HELP YOUIF YOU LIKE MY ANSWER PLEASE RATE AND HELP ME IT IS VERY IMP FOR ME