Understanding Set collection in Java with real life example

Here we will learn about what is Set Interface and when we should use it. I usually use sets, when I need a fast implementation because Sets have extra overhead in time and memory as sets are usually backed by a HashMap or a Tree.

Now coming back to real life examples of a set interface, we have seen that in kitchen, Utensils are arranged in such a manner that plates are kept separately from the spoons. Another example is when we visit mobile showrooms, we observe that smartphones are separated from the simple mobiles.

The Set Interface

  • Set Interface extends Collection.
  • It does not allow duplication of elements. If duplicate elements are added, add method returns false.
  • equals method is used for comparison.
  • The classes that implements Set Interface HashSet, LinkedHashSet and TreeSet.

The HashSet Class

  • It extends AbstractSet class and implements Set Interface.
  • This class creates a collection using hashing mechanism. (hashCode is used as key to access data).
  • It is unordered as well as unsorted with no duplicate values.
  • NOTE: If no order is required while iterating use HashSet.
  • Classes that are to be stored in a HashSet must implement the hashCode() and equals() method.

The LinkedHashSet Class

  • It extends HashSet.
  • Maintains a linked list of elements in HashSet in the ordered they are inserted (doubly).
  • NOTE: If the order is required while iterating use LinkedHashSet.

The TreeSet Class

  • The TreeSet class implements the Set interface and stores elements in the form of a tree.
  • Arranges elements in Ascending order.
  • Used when fast retrieval is required and large size of data needs to be stored.
  • With Java 6, this class implements NavigableSet interface.

TreeSet does add several new methods to the Set interface.

1.Object first() – It gets the first element from the sorted set.
2.Object last() – It gets the last element from the sorted set.
3.SortedSet headSet(Object toElement) – It will return a view of the portion of this set whose elements are less than toElement.
4.SortedSet tailSet(Object fromElement) – It will return a view of the portion of this set whose elements are greater than or equal to fromElement.
5.SortedSet subSet(Object fromElement, Object toElement) – It will return a view of the portion of this set whose starting element is greater than or equal to fromElement and whose ending element is less than toElement.

SET Collection

Here are some of the key methods of the Set interface:

  • boolean add(Object) – Ensures that the Set holds an argument. The Object is added only if it isn’t already in the Set. Returns false if the Object was not added to the Set.

Example:

Set names = new HashSet<>();
names.add("Tom");
names.add("jerry");

if (names.add("Dog")) {
System.out.println("Dog is added to the set");
}

if (!names.add("Tom")) {
System.out.println("Tom is already added to the set");
}
  • void clear() – Removes all elements from Set.

Example:

names.clear();

if (names.isEmpty()) {
System.out.println("The set is empty");
}
  • boolean contains(Object) – Returns true if the Set contains the argument.

Example:

Set names = new HashSet<>();
names.add("Tom");
names.add("Mary");
names.add("Peter");
names.add("Alice");

if (names.contains("Mary")) {
System.out.println("Found Mary");
}
  • boolean isEmpty() – Returns true if the Set contains no elements.

Example:

if (names.isEmpty()) {
System.out.println("The set is empty");
} else {
System.out.println("The set is not empty");
}
  • Iterator iterator()Returns an Iterator object which can be used to traverse through the Set.

Example:

Set names = new HashSet<>();
names.add("Tom");
names.add("jerry");
names.add("jack");
names.add("jones");
Iterator iterator = names.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
System.out.println(name);
}
  • boolean removeAll(Object) – Removes the argument from the Set.

Example:

Set s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 7, 9));
Set s2 = new HashSet<>(Arrays.asList(2, 4, 6, 8));
System.out.println("s1 before difference: " + s1);
s1.removeAll(s2);
System.out.println("s1 after difference: " + s1);
  • int size() – Returns the number of elements in the Set.

Example:

Set names = new HashSet<>();
names.add("Tom");
names.add("jerry");
names.add("jack");
names.add("jones");

System.out.printf("The set has %d elements", names.size());