A Set in Java is a collection of data elements where every item is unique. This lesson will show you how to walk through a Set in Java, providing working code examples along the way.

Java Sets

A Set in Java is a collection of items, each of the same data type, and none of which are duplicates. This lesson will cover two major sets: one is ordered, and the other is not. Set is part of a larger Java class, called Collections. Set is an interface in the collections class, but in order to use any of the methods within it, we need to import the Java utility packages.

We Will Write a Custom Essay Specifically
For You For Only $13.90/page!


order now

This code must go before any class declaration in your code:


import java.util.*;


Okay, now that we have the utility imported, we can start using it.

Creating & Iterating in the Set

First, let’s create our set. We will be creating a HashSet, which is a truly unordered set. Also, a TreeSet will maintain items in ascending order.

In our example, we’ll start with a HashSet and then loop through it. This code shows how to create a new Set using the Set interface. You define the type, provide a variable for the set, and then tell Java to create a new HashSet:


//create our Set
Set < String > trees = new HashSet();
trees.add("Larch");
trees.add("Pine");
trees.add("Balsam"Balsam");
trees.add("Birch");
trees.add("Ash");


One way to loop through a Set is the trusty ‘for’ loop. We can quickly walk through each item in the Set and display the output. The code for this looks like this:


//iterate over set
for (String s: trees) {
  System.out.println("Tree = " + s);
}


The ‘for’ loop, in this case, establishes the type (String), a counter (s), and the Set (trees). When the program runs, we get a printout of our trees, as seen here:


Java loop set output


Notice how the order doesn’t match the order we entered the trees. This highlights the unordered nature of the HashSet. In fact, until we compile and run the program, we really won’t know what order the list will be in.

This does not mean the order is random. The order is actually determined by Java. Once the set is built and compiled, the order (or un-order, as it were) is set. You don’t have control over it, but you could run and re-run the code and get the same (un) order.

There is another loop we can use, known as the ‘forEach loop,’ which is a variation of the ‘for’ loop. It is only in Java versions 8 and older, so if you are on an older version, this will not work. The loop uses the forEach method and is accessed by first referencing the Set (trees). You can then display the output, though the code is a little different than we’ve seen before.


tree.forEach(System.out::println);


When it is run, the same output displays:


Java for each iterate Set output


Now it’s the fun part! We will make use of the Java Iterator interface, which lets you cycle through lists and sets. In order to use it, you need to create a new instance of the Iterator.

Next, we make use of a ‘while’ loop that runs while the set has a next item to look for. The Iterator interface provides us with a method, hasNext(), which returns false if there are no more members. Inside the ‘while’ loop, we display some info and the value from the set. To get the value, the method is next(). The data type for the Iterator interface must match the data type of the set.


Iterator ; String ; ir = trees.iterator();
while (ir.hasNext()) {
; System.out.println(;Iterator Result = ; + ir.next());
}


When this runs, we get a similar output, which is still unordered, and looks like this:


Java Iterate set output


A Different Set

Now that we’ve covered iterating through a HashSet, let’s take a look at how this would look with a TreeSet. Remember that our output for the HashSet was somewhat random. Again, we will create the same list, except the set is now a TreeSet, and then loop over the set using Iterator. Also, we moved a few trees around so they would not be in any order.


//create our Set
Set ; String ; trees = new TreeSet();
trees.add(;Larch;);
trees.add(;Pine;);
trees.add(;Balsam;Balsam;);
trees.add(;Birch;);
trees.add(;Ash;);
Iterator ; String ; ir = trees.iterator();
while (ir.hasNext()) {
; System.out.println(;Iterator Result = ; + ir.next());
}


When this code processes, you’ll notice that the display is actually displayed in ascending order, like this:


Java sets TreeSet output


This works with other data types as well. Consider this TreeSet that is setup with Double data types:


Set < Double > scores = new TreeSet();
scores.add(1.59343);
scores.add(.9934847);
scores.add(-3.3444);
Iterator < Double > ir = scores.iterator();
while (ir.hasNext()) {
 System.out.println("Score: " + ir.next());
}


Thus, the output is ascending:


Double treesets output


While the ‘for’ loops are acceptable iterators of a set, the Iterator interface is part of the Collections class and so it is a great fit with sets. If you use HashSet or TreeSet, the code is the same to loop through them, just be aware the TreeSet will be in ascending order.

Lesson Summary

To recap, a Set in Java is a collection of objects. It is really an interface that is part of the Collections class. A HashSet is unordered, while a TreeSet is stored in ascending order. We can iterate over these sets using a ‘for’ loop, a ‘forEach’ loop, or by making use of the Iterator interface, which lets you cycle through lists and sets. Iterator provides methods for determining the next element and accessing elements in the set.