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.
Likewise, we can use TreeSet with user-defined objects. However, the corresponding class must implement the Comparable interface. The following example demonstrates it.
Unlike TreeSet, a HashSet is an unordered and unsorted set. The following example demonstrates how to use a HashSet collection.
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.
The following list provides some Examples of Sets in Java.
- 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.
- 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
- 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.
- Implement the above program using a TreeSet Collection.
- Dot Net Framework
- Power Bi
- Scratch 3.0