Start learning with our library of video tutorials taught by experts. Get started

Java Essential Training
Illustration by

Looping through collections with iterators


From:

Java Essential Training

with David Gassner

Video: Looping through collections with iterators

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.
Expand all | Collapse all
  1. 10m 8s
    1. Welcome
      1m 3s
    2. Is this course for you?
      5m 35s
    3. Using the exercise files
      3m 30s
  2. 31m 24s
    1. The history of Java
      5m 19s
    2. Java compilation and syntax
      8m 54s
    3. Understanding the principles of Java
      8m 28s
    4. Choosing a development environment
      8m 43s
  3. 19m 5s
    1. Installing Java on Windows
      6m 42s
    2. Installing Eclipse on Windows
      3m 19s
    3. Exploring Java on Mac OS X Leopard and Snow Leopard
      2m 27s
    4. Installing Java on Mac OS X Lion
      3m 27s
    5. Installing Eclipse on Mac OS X
      3m 10s
  4. 46m 10s
    1. Creating a Hello World application
      11m 7s
    2. Exploring the Eclipse IDE
      8m 55s
    3. Compiling and running from the command line
      8m 2s
    4. Passing arguments to the application
      8m 17s
    5. Using the Java API documentation
      4m 5s
    6. Memory management and garbage collection
      5m 44s
  5. 58m 57s
    1. Everything is an object
      5m 59s
    2. Declaring and initializing variables
      9m 15s
    3. Working with numbers
      8m 32s
    4. Converting numeric values
      6m 40s
    5. Understanding operators
      7m 58s
    6. Working with character values
      5m 14s
    7. Working with boolean values
      5m 13s
    8. Outputting primitive values as strings
      5m 33s
    9. Creating a simple calculator application
      4m 33s
  6. 53m 40s
    1. Writing conditional code
      5m 35s
    2. Using the switch statement
      8m 50s
    3. Repeating code blocks with loops
      7m 35s
    4. Creating reusable code with methods
      6m 31s
    5. Declaring methods with arguments
      5m 41s
    6. Overloading method names with different signatures
      5m 53s
    7. Passing arguments by reference or by value
      5m 35s
    8. Creating a more complex calculator application
      8m 0s
  7. 20m 30s
    1. Using the String class
      5m 44s
    2. Building strings with StringBuilder
      3m 34s
    3. Parsing string values
      3m 19s
    4. Working with date values
      7m 53s
  8. 20m 44s
    1. Understanding compile-time vs. runtime errors
      4m 5s
    2. Handling exceptions with try/catch
      4m 55s
    3. Throwing exceptions in methods
      2m 50s
    4. Using the debugger
      8m 54s
  9. 32m 22s
    1. Using simple arrays
      4m 47s
    2. Using two-dimensional arrays
      6m 17s
    3. Managing resizable arrays with ArrayList
      7m 14s
    4. Managing unordered data with HashMap
      6m 5s
    5. Looping through collections with iterators
      7m 59s
  10. 52m 2s
    1. Understanding encapsulation
      5m 59s
    2. Creating and instantiating custom classes
      8m 8s
    3. Organizing classes with packages
      6m 47s
    4. Creating and using instance methods
      6m 52s
    5. Storing data in instance variables
      6m 56s
    6. Using constructor methods
      5m 40s
    7. Managing instance data with getter and setter methods
      8m 26s
    8. Using class variables and Enum classes
      3m 14s
  11. 41m 15s
    1. Understanding inheritance and polymorphism
      9m 12s
    2. Extending custom classes
      9m 1s
    3. Overriding superclass methods
      3m 8s
    4. Casting subclass objects
      5m 3s
    5. Understanding interfaces and implementing classes
      4m 2s
    6. Creating your own interfaces
      4m 14s
    7. Using abstract classes and methods
      6m 35s
  12. 32m 17s
    1. Managing files with the core class library
      7m 46s
    2. Managing files with Apache Commons FileUtils
      7m 32s
    3. Reading a text file from a networked resource
      7m 52s
    4. Parsing an XML file with DOM
      9m 7s
  13. 17m 39s
    1. Creating your own JAR files
      4m 54s
    2. Understanding the classpath
      5m 2s
    3. Documenting code with Javadoc
      7m 43s
  14. 47s
    1. Goodbye
      47s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
please wait ...
Java Essential Training
7h 17m Beginner Dec 14, 2011

Viewers: in countries Watching now:

Join author David Gassner as he explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more. This course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts.

Topics include:
  • Understanding the history and principles of Java
  • Installing Eclipse and Java
  • Compiling and running from the command line
  • Managing memory and performing garbage collection
  • Declaring and initializing variables
  • Writing conditional code
  • Building and parsing strings
  • Debugging and exception handling
  • Using simple arrays
  • Creating custom classes
  • Working with encapsulation, inheritance, and polymorphism
  • Managing files
  • Documenting code with Javadocs
Subjects:
Developer Programming Languages
Software:
Android Java Eclipse
Author:
David Gassner

Looping through collections with iterators

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.

There are currently no FAQs about Java Essential Training.

 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now Upgrade now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Java Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

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.

Are you sure you want to delete this note?

No

Notes cannot be added for locked videos.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.