In this lab, we will explore and demonstrate HashSet and TreeSet. We will utilize the built-in methods.
Learning Objective
By the end of this lab, learners will be able to explain and use HashSet and TreeSet.
HashSet Examples
Example One: Insert Elements to HashSet using addAll().
addAll() - Inserts all of the elements of the specified collection to the set. Create a new Java project and create a new Class named “exampleOne.” Write the code below in the class.
importjava.util.HashSet;publicclassexampleOne {publicstaticvoidmain(String[] args) {HashSet<Integer> evenNumber =newHashSet<>();// Using add() methodevenNumber.add(2);evenNumber.add(4);evenNumber.add(6);System.out.println("HashSet: "+ evenNumber);HashSet<Integer> numbers =newHashSet<>();// Using addAll() methodnumbers.addAll(evenNumber);numbers.add(5);System.out.println("New HashSet: "+ numbers); }}
Output:
HashSet: [2, 4, 6]
New HashSet: [2, 4, 5, 6]
Example Two: Union of Sets.
To perform the union between two sets, we can use the addAll() method.
Create a new Class named “exampletwo,” and then write the code below in the class.
importjava.util.HashSet;publicclassexampletwo {publicstaticvoidmain(String[] args) {HashSet<Integer> evenNumbers =newHashSet<>();evenNumbers.add(2);evenNumbers.add(4);System.out.println("HashSet1: "+ evenNumbers);HashSet<Integer> numbers =newHashSet<>();numbers.add(1);numbers.add(3);System.out.println("HashSet2: "+ numbers);// Union of two setnumbers.addAll(evenNumbers);System.out.println("Union is: "+ numbers); }}
Output
HashSet1: [2, 4]
HashSet2: [1, 3]
Union is: [1, 2, 3, 4]
Example Three: Difference of Sets.
To calculate the difference between the two sets, we can use the removeAll() method: Create a new Class named “examplethree,” and then write the code below in the class.
Create a new Class named “examplefour,” and then write the code below in the class.
importjava.util.HashSet;publicclassExamplefour {publicstaticvoidmain(String args[]) {// HashSet declarationHashSet<String> hset =newHashSet<String>();// Adding elements to the HashSethset.add("Apple");hset.add("Mango");hset.add("Grapes");hset.add("Orange");hset.add("Fig");//Addition of duplicate elementshset.add("Apple");hset.add("Mango");//Addition of null valueshset.add(null);hset.add(null);// Using advanced for loopfor (String str : hset) {System.out.println(" ---> "+ str); } }}
Remember: HashSet DOES NOT maintain any order, so this order might be changed if you run your code a second time.
TreeSet Examples
Example one: Iterate Through TreeSet.
To access the individual elements of TreeSet, we need to iterate through the TreeSet —— traverse through the TreeSet. We do this by declaring an Iterator for the TreeSet, and then use that Iterator to access each element. For this, we use the next() method of an iterator that returns the next element in the TreeSet.
The following Java program demonstrates the use of the Iterator to iterate through TreeSet.
importjava.util.TreeSet;importjava.util.Iterator;publicclassTreesetExampleone {publicstaticvoidmain(String[] args) {TreeSet<Integer> num_Treeset =newTreeSet<>();num_Treeset.add(20);num_Treeset.add(5);num_Treeset.add(15);num_Treeset.add(25);num_Treeset.add(10);// Call iterator() method to define Iterator for TreeSetIterator<Integer> iter_set =num_Treeset.iterator();System.out.print("TreeSet using Iterator: ");// Access TreeSet elements using Iteratorwhile(iter_set.hasNext()) {System.out.print(iter_set.next());System.out.print(", "); } }}
Output;
TreeSet using Iterator: 5, 10, 15, 20, 25,
Example two: Remove Elements
remove() - removes the specified element from the set. removeAll() - removes all of the elements from the set.
importjava.util.TreeSet;publicclassTreesetExampletwo {publicstaticvoidmain(String[] args) {TreeSet<Integer> numbers =newTreeSet<>();numbers.add(2);numbers.add(5);numbers.add(6);System.out.println("TreeSet: "+ numbers);// Using the remove() methodboolean value1 =numbers.remove(5);System.out.println("Is 5 removed? "+ value1);// Using the removeAll() methodboolean value2 =numbers.removeAll(numbers);System.out.println("Are all elements removed? "+ value2); }}
Output:
TreeSet: [2, 5, 6]
Is 5 removed? true
Are all elements removed? true
Example three: Methods for Navigation.
Since the TreeSet class implements NavigableSet, it provides various methods to navigate over the elements of the TreeSet.
first() and last() Methods first() - returns the first element of the set. last() - returns the last element of the set.
importjava.util.TreeSet;publicclassTreesetExamplethree {publicstaticvoidmain(String[] args) {TreeSet<Integer> numbers =newTreeSet<>();numbers.add(2);numbers.add(5);numbers.add(6);System.out.println("TreeSet: "+ numbers);// Using the first() methodint first =numbers.first();System.out.println("First Number: "+ first);// Using the last() methodint last =numbers.last();System.out.println("Last Number: "+ last); }}
Output:
TreeSet: [5, 10, 15, 20, 25]
First Number: 5
Last Number: 25
Example four: sort the given TreeSet alphabetically in reverse order.
In this example, we will implement a Comparator class to sort the given TreeSet alphabetically in reverse order. By default, the TreeSet sorts data in ascending order. We can also sort TreeSet in a customized order by defining a new comparator class. In this comparator class, we need to override the ‘compare’ method to sort the elements of the TreeSet. This comparator object is then passed to the TreeSet constructor.
Create a class named “cities_Comparator” and add the code below:
importjava.util.Comparator;publicclasscities_ComparatorimplementsComparator<String> {//override compare method to compare two elements of the TreeSet@Overridepublicintcompare(String cities_one,String cities_two) {int value =cities_one.compareTo(cities_two);// sort elements in reverse orderif (value >0) {return-1; }elseif (value <0) {return1; }else {return0; } } }
Create a class named “TreeSetExampleCom” and add the code below:
importjava.util.TreeSet;publicclassTreeSetExampleCom {publicstaticvoidmain(String[] args) {// Create a TreeSet with user-defined comparatorTreeSet<String> cities =newTreeSet<>(newcities_Comparator());//add elements to the comparatorcities.add("UAE");cities.add("Mumbai");cities.add("NewYork");cities.add("Hyderabad");cities.add("Karachi");cities.add("Xanadu");cities.add("Lahore");cities.add("Zagazig");cities.add("Yingkou");//print the contents of TreeSetSystem.out.println("TreeSet: "+ cities); }}