Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
When you loop through a simple array in Java, you typically use a for loop and a counter variable or a foreach loop. If you're using the counter variable approach, you increment that variable once each time through the loop and then use that as an index value. You could do that with an array list, but the array list and the HashMap both have more elegant approaches available for iterating or looping through their contents. There's a pattern called an iterator, an iterator is a special Java class that's designed to allow you to loop without having to keep track of internal numbering yourself.
I'll show you how to use iterators on both the array list and the HashMap. I'm working in a project called iterators, which is a part of this chapter's exercise files. The beginning code for this application declares an array list named list and a HashMap named Map. Items are added to each of the objects, and then the objects are output to the Console. I'll run the application and show the results. Now because these classes are not members of java.lang, at the top of the class you'll see these import statements, these are critical.
Now, I'll show you how to create an iterator from an array list. The first step is that you need to know what kind of class you're going to be getting. For an array list, the iterator is called a list iterator and there was a special class for it. I'll declare a class named ListIterator, notice that there are two available, I'll choose the one from java.util. And when I declare the data type, just like the array list, I need to declare the data type of its values. In this case, it will be string.
I'll give this variable a name of listIterator with a lowercase initial character. Now to populate its value, I'll call the array list objects listIterator method, this returns the iterator that references the list values. I now have an object that I can use to easily loop through the values. Next I'll use a while loop, I'll type in the keyword while and press control space and I'll choose this version while loop with condition.
It's up to me to determine what that condition is. The listIterator object has a method called hasNext. As long as there is an available next item in the collection, it will return true. When I have dealt with the last item in the collection, it will return false. So my condition will be listIterator.hasNext. Within the code block for the while loop, I'll now create a string variable and I'll give it a variable name, value. And in order to get the next item from the iterator, I use this code listIterator.next.
When you call the next method, it moves internally to the next item within the iterator and the collection and it returns a reference to the value. If it's complex object, it's a reference to the object. Now I can output the value. I'll use System.out.println and just value. So that's how use the listIterator when you're working with an array list object. I'll run the application and show that it's outputting in turn California, Oregon and Washington.
Because I started from an array list which is an ordered collection, it's guaranteed that I'll be looping through in the order in which the items were placed into the list. So now I'll show you how to do something fairly similar with a HashMap. Remember that this HashMap has two sets of strings, the keys and the values. You can iterate through either. But I'm going to focus on iterating through the keys because once you have a key, you can get to the value. With an array list, it's a single step to get to the iterator you need.
But with a HashMap it's two steps. The first step is to get the collection of strings that you want to loop through and the second step is to get the iterator. With the HashMap class you can either get the values using the method values or you can get a set of values called a key set and that would be the set of keys California, Oregon and Washington. When you get the keys, they'll end up in an object called a Set. Type in the word Set and press Ctrl+ Spacebar and choose the set class from java.util.
And as with all classes in the collections framework set the data type, I'll set it to string. Now to populate that set of values called map.keySet. Now as I've been typing, I should've been getting import statements at the top of the code. If you aren't getting your import statements for any reason, you can easily fix that by pressing Ctrl + Shift + O on Windows or Command + shift + O on Mac, and Eclipse will fix up your imports making sure you have the ones you need and putting them in the right order.
Now let's go back to the code. I'm missing my variable name here and I'll just call it keys. Okay now I'm ready to create my iterator. When you're working with a set, and you want to iterate through its values, instead of getting a list iterator you'll get a class simply named iterator. At this point, you might be asking how do I know this? And the answer is it's in the documentation. Remember that because Java is so strongly typed, every bit of documentation will tell you exactly what you're getting.
So I'm going to create a class which is data type as an iterator. Again make sure you choose the right version, this one should be from java.util, set the data type, and set the variable name, I'll call it iterator. And then get the value of the iterator from keys.iterator the method. Now I'm ready to loop. I'll go to the next line and type while and press Ctrl+ Spacebar once again I'll choose while loop with condition. And the programming interfaces of the iterator and the list iterator are exactly the same.
So I'll be able to use while iterator.hasNext. And within the while loop, I'll once again declare a string, I'll set its name to a value, I'll get its value from iterator.next, again following exactly the same syntax that I did with the listIterator and then I'll output the value System.out.println. I'll run the application and I get California, Oregon and Washington.
But remember, those key values came from a HashMap, but remember those strings are keys in a HashMap and each key has an associated value, so I'm going to do this with a little bit more complexity. I'll expand my editor, so I have a little bit more width to work with, and I'll add before the value the capital of, and then the value, and then after that I add another plus operator and a space is, and then after another space and another quote, another plus operator and then map.get(value).
So the whole purpose of this was to loop through the keys, so that I could then address the keys and their associated values, here is the result the capitol of California is Sacramento and so on. Iterators always work on collections of single values. When you're working with a HashMap you're working with a collection of keys and associated values. So the first step is to extract the keys and the next step is to get the iterator so you can loop through the contents. Iterators are a valuable part of what's known as the collections framework in Java.
They're designed to make it very easy to loop through the contents of your data in memory without having to keep track of your own numeric counter variables or use your own handcrafted strategies.
Get unlimited access to all courses for just $25/month.Become a member
82 Video lessons · 98139 Viewers
61 Video lessons · 85445 Viewers
71 Video lessons · 69415 Viewers
56 Video lessons · 101769 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.
Your file was successfully uploaded.