In: Computer Science
IN JAVA PLEASE
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
Sample output:
ArrayList: [2, 4, 4, 0, 4, 0, 1, 5, 5, 5]
TreeSet: [0, 1, 2, 4, 5]
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
// instantiating random class
Random rand = new Random();
// setting seed to 5
rand.setSeed(5);
int randMax = 6;
ArrayList<Integer> numAL = new ArrayList<>();
// generating 10 random numbers and adding to numAL
for(int i=0 ; i<10 ; i++) {
int num = rand.nextInt(randMax + 1);
numAL.add(num);
}
System.out.println("ArrayList : "+numAL);
// instantiating TreeSet and Iterator
TreeSet<Integer> numTS = new TreeSet<>();
Iterator<Integer> allIter = numAL.iterator();
// iterating through every element and adding to TreeSet
while (allIter.hasNext()) {
numTS.add(allIter.next());
}
System.out.println("TreeSet : "+numTS);
}
}
Code
Output