Java Sets

Like lists and arrays, sets can contain multiple values of the same type. They share the flexibility of lists, but have the added feature that they cannot hold duplicate values. In Java, there are a number of different types of set, out of which two will be discussed here, ‘HashSet’ and ‘TreeSet’.

In order to use sets, ‘java.util.Set’ needs to be imported. Depending on which of the two above types of set are used, a further import needs to be included, ‘java.util.HashSet’ or ‘java.util.TreeSet’.

The difference between these two types of set is that a ‘HashSet’ doesn’t maintain an order of the items within it, whereas a ‘TreeSet’ does.

Below is an example of how both of these types of set are declared, where ‘nameHashSet’ and ‘nameTreeSet’ are the names for the respective sets, with each being able to hold string values.

Set<String> nameHashSet = new HashSet<String>();
Set<String> nameTreeSet = new TreeSet<String>();

Below are examples of how items can be added to these sets and then subsequently displayed in the console using a ‘foreach’ loop.

nameHashSet.add("George");
nameHashSet.add("Bob");
nameHashSet.add("Fred");
nameHashSet.add("Andrew");

nameTreeSet.add("George");
nameTreeSet.add("Bob");
nameTreeSet.add("Fred");
nameTreeSet.add("Andrew");

System.out.println("HashSet:");

for (String name : nameHashSet)
{
   System.out.println(name);
}

System.out.println();
System.out.println("TreeSet:");

for (String name : nameTreeSet)
{
   System.out.println(name);
}

The output from the above is where the difference between the two sets can be seen, where the names in the ‘HashSet’ are in no particular order, but in the ‘TreeSet’ they are displayed alphabetically.

HashSet:
George
Bob
Andrew
Fred

TreeSet:
Andrew
Bob
Fred
George

As previously mentioned, a set cannot contain duplicate items, however, if an attempt is made to add a duplicate, no error is produced and no new item gets added.

Removing an item from a set is done in a similar fashion to adding.

nameHashSet.remove("Bob");
nameTreeSet.remove("Bob");

If there is a need to check to see if an item exists within a set, then the ‘contains’ method can be used with both a ‘HashSet’ and a ‘TreeSet’. The ‘contains’ method is used in the examples below to check for the existence of the name ‘George’ in both the sets and display a message to the console if it is found.

if (nameHashSet.contains("George"))
{
   System.out.println("George is in the HashSet");
}

if (nameTreeSet.contains("George"))
{
   System.out.println("George is in the TreeSet");
}

Further Reading