How to Iterate Set in Java

An error occurred trying to load this video.

Try refreshing the page, or contact customer support.

Coming up next: Java Random: Method & Examples

You're on a roll. Keep up the good work!

Take Quiz Watch Next Lesson
Your next lesson will play in 10 seconds
  • 0:04 Java Sets
  • 0:38 Creating & Iterating…
  • 3:08 A Different Set
  • 4:04 Lesson Summary
Save Save Save

Want to watch this again later?

Log in or sign up to add this lesson to a Custom Course.

Log in or Sign up

Speed Speed

Recommended Lessons and Courses for You

Lesson Transcript
Instructor: Martin Gibbs

Martin has 16 years experience in Human Resources Information Systems and has a PhD in Information Technology Management. He is an adjunct professor of computer science and computer programming.

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.

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();

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 newer, 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.


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.

To unlock this lesson you must be a Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use

Become a member and start learning now.
Become a Member  Back
What teachers are saying about
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 200 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create an account