Join David Gassner for an in-depth discussion in this video Looping through collections with iterators and for-each, part of Java 8 Essential Training.
- Java gives you a number of ways of looping through or iterating through collections of data, either ordered or unordered data. I'm going to demonstrate some of these techniques in the project "IterateCollections". I'm starting with an ArrayList declared at line 13 and it contains three items, and in line 19 I'm outputting that list using simple output passing the object to print line, and that cause the two-string method of the object. When I run the application I get the data printed out with the standard formatting.
Now I'm going to describe how to use something called an Iterator object, this used to be the most common way of looping through a collection. You create something called an Iterator object and there's an interface available for this, and notice up at the top that now I have an import statement that says "java.util.*". IntelliJ IDEA has decided that I'm using so many interfaces and classes from this package that instead of importing them individually it's just going to import the entire package.
That doesn't affect performance at all it's simply a way of reducing the amount of code. An Iterator resembles to the other collection interfaces in that it takes generic notation, so you can indicate what kind of data you're looping on. I'll see I'm looping on a String, and I'll name this object simply "iterator". Then I'll call the "list" object and its iterator method, and that returns a reference to an Iterator object that I can use to loop through the list.
In order to loop through the data using an Iterator you'll use two methods: a method that return a Boolean called "hasNext" that indicates whether there's available data in the object you're looping through, and then another method named "next" that moves to the next available object and returns a reference to it. I'll create a While loop and my condition will be "iterator.hasNext()", then within the loop I'll create a String that I'll name "value", and then I'll call "iterator.next()", and then I'll output that String.
So this is the code you need: you get the Iterator object, then you create a loop and within the loop you get the reference to the object and you do whatever you need to do with it, and when you run the code you get the output. You can also loop through an ArrayList using a ForEach statement. I'll create a For loop, and within the For loop I'll create a String, I'll name it "value", and then after a colon I'll say I'm getting the data from my "list", and within the list I can output the value, and there's the result.
It's exactly the same output but I don't need the additional object that the Iterator requires so it's a little bit more memory-efficient and takes less code. And finally another technique was introduced that you can use for this in Java 8 called Method References. I have a loop containing Strings, and let's say I have a method of some object that's accepting a single String argument, I can simply say, "Use this method" and the compiler takes care of everything else.
I'll call "list.forEach". Now, be warned, this method only exists in Java 8 and later, it doesn't exist in Java 7 and it doesn't exist in Android's version of Java. Next I'll pass in a class that has a static method I wanna use, I'll call "System.out", then I'll put in a pair of colons, and then the name of the method I want to call, "println". Now, the logic is the "println" method accepts a String, I'm passing the object and compiler says, "Each of the items in the list is a String", so it then calls the method for you and passes the String in.
I'll run that code, and again I see exactly the same output. In Java 8 this is unquestionably the most efficient, not just in terms of performance but in terms of the amount of code you have to write. You can also loop through unordered data. I'm going to uncomment the rest of this code and now I have a Map containing three items, each item has a key and a value, and if I run the code I get an output of the data using the default formatting of the two-string method of the List interface, but now I'll use a HashMap Iterator.
First I need to get a Set of keys, a Set is similar to a List in that it contains ordered data but it guarantees uniqueness and that's not something that an ArrayList would do. I'll create a Set and I'll set the data type of the items in the Set as String, and I'll name it "keys", then I'll call the method "map.keySet()". The "keySet" method returns a Set, and now I have a unique set of keys that I can use to reference the items in the map.
Next I'll create an Iterator, once again I'll set the generic data type as String and I'll name this one "iterator1", ad I'll call the method "keys.iterator()". Next I'll use a While loop, my condition will be "iterator1.hasNext()", and then within the loop I'll create a String, then I'll call "iterator1.next()" and now I have the current key, and then I'll output "The capital of" and then I'll append the key, then another little string and then the value with "map.get()" and I'll pass in the key.
So using an Iterator on a HashMap takes a bit of code but it absolutely works. And I see the output of the three states and their capitals, and just like an ArrayList you can use a ForEach loop on a Map. I'll use that same set of keys and this time I'll create a For loop, and then within the parentheses I'll create a "key" variable, a String, and I'll get its value from the "keys" collection, and within the loop I'll output the same value, I'll just copy and paste this bit of code.
And there's the result. So you have Iterators, you have ForEach loops, and in Java 8 you have Method References. You can use any of these three coding strategies to loop through or iterate through a collection of data.
- Understanding the history and principles of Java
- Installing Java, IntelliJ IDEA, and BlueJ
- Creating a Java project
- Working with variables, values, and expressions
- Working with object data types
- Building, comparing, and parsing strings
- Debugging and exception handling
- Creating loops and reusable code
- Passing arguments by reference or value
- Using simple and complex arrays
- Creating custom classes
- Understanding inheritance and polymorphism
- Managing files with Java libraries
- Documenting code with Javadoc
- Packaging classes in JAR files