Examples of Sets in Java

0
12

This article demonstrates some examples of Sets in Java.

The Set Interface in Java

Basically, it is an unordered collection and doesn’t allow duplicates. When you add a duplicate element, it will replace the existing one. TreeSet class implements the Set interface. It represents a sorted collection. When we need to store the user defined objects in TreeSet, then we need to implement the Comparable interface and to define the compareTo() method.

The following example demonstrates how to use a TreeSet with String objects.

Example of Using TreeSet

Likewise, we can use TreeSet with user-defined objects. However, the corresponding class must implement the Comparable interface. The following example demonstrates it.

Example of Using TreeSet with Emp Objects

Unlike TreeSet, a HashSet is an unordered and unsorted set. The following example demonstrates how to use a HashSet collection.

Example of Using HashSet

Like TreeSet, a HashSet can also store user-defined objects. However, the corresponding class must implement the Comparable interface and define the compareTo() method. The following example demonstrates a HashSet created with the objects of the Emp class.

Example of HashSet Using Emp Objects

The following list provides some examples of Sets in Java.

  1. Define a class Book and store a collection of Books in a HashSet. Also, retrieve and display all elements of the HashSet using an iterator.
  2. When do we use TreeSet Collection? Write a program in Java to store strings in a TreeSet. The following operations need to be performed on the TreeSet: (i) Reverse the collection (ii) Search for an element (iii) Iterate over all the elements
  3. Create a class that has a HashSet collection as the dataset to store the name of colors. Also, define a method addColorName(String color) to add color to the HashSet and a method to display all the colors in the HashSet.
  4. Implement the above program using a TreeSet Collection.

Further Reading

30+ Basic Java Programs

Java Practice Exercise

Princites

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here