Iterating over a collection is a task that most developers are required to perform during their development task and most of us keep on using the same way which we have used earlier though there are many ways to do this.
In this post I am going to list down all those ways. We all might be familiar with these ways.
Still, keep on reading to refresh!!!
First let’s initialize a list
List list = Arrays.asList(new String[]{
"first","second","third","fourth", "fifth"
});
Now let’s begin iteration:
Method 1: Using for loop
for (int count = 0; count < list.size(); count++) {
System.out.println("Item:: " + list.get(count));
}
Detail
Iterate over the list using a for
loop which runs from 0 to the total number of list elements - 1. This is because elements of the list are indexed from 0.
In every iteration, retrieve the current list element using its get
method. get
accepts the index as argument and returns the element at that index.
Method 2: Using advanced for loop(for-each loop)
for (String s : list) {
System.out.println("Item:: " + s);
}
Detail
This example uses an enhanced for loop to iterate over a collection. In this loop, the loop variable has the current list item as its value and it should be of the same type as the elements of the list, which is a String in this case.
Method 3: Using java.util.Iterator
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println("Item:: " + iterator.next());
}
Detail
This method uses a java.util.iterator
to iterate over the list. You can get an iterator over the list using its iterator()
method.
An iterator has a next()
method which returns the list element at the current iterator position. It also contains hasNext()
method which returns true
if the list has any more elements after the current iterator position.
This method is primarily used for iterating over a Set.
Method 4: Using java8
list.forEach(new Consumer() {
public void accept(String s) {
System.out.println("Item :: "+s);
}
});
Detail
forEach
method of java.lang.Iterable
interface is used to loop over a collection. This method takes a java.util.function.Consumer
interface object which has an accept
method.
accept
takes a single argument and returns nothing. In each iteration, we are passing an element to this method and printing it out to the console.
There is another variant of above method which uses Lambda expression as:
list.forEach(s -> {
s = "Item :: " + s;
System.out.println(s);
});
Detail: Since java.util.function.Consumer
interface is a Functional interface, we may use Lambda Expression where this interface type is expected as an argument. forEach
method of java.lang.Iterable
expects a java.util.function.Consumer
type in its accept method. Hence, we are passing Lambda Expression to perform the same task.
Method 5: Iterate list java 8
list.stream().forEach(s -> {
s = "Item :: " + s;
System.out.println(s);
});
Detail
Similar to the above method, we are utilizing a stream over the list object. stream()
method is a new addition to java.util.Collection
interface in java 8 and is a
default interface method which returns a java.util.stream.Stream
instance.
java.util.stream.Stream
has a forEach
method which accepts a java.util.function.Consumer
object as an argument. Rest functionality is the same as Method 4 above.
Method 6: Using a ListIterator
This method is similar to using an iterator. java.util.List
has a listIterator()
method which returns a java.util.ListIterator
for iterating over a list.
ListIterator also contains hasNext()
and next()
methods which are used for list iteration as shown below.
ListIterator iterator = list.listIterator();
while (iterator.hasNext()) {
System.out.println("Item:: " + iterator.next());
}
An advantage of using a ListIterator is that it can also be used to iterate a list in reverse order as opposed to a conventional iterator.
Let’s tweak in
- Method 1 may throw
ArrayIndexOutOfBoundsException
if you do a get(count) and count exceeds size of list. - Method 3 is primarily used for iterating over a set since, unlike a List, a Set does NOT have a get() method to get its individual elements.
- When using iterator always check the condition using
hasNext
method of iterator.
Never checknull
onnext()
method (likeif(iterator.next() != null)
) sincenext()
method will return a list element and move the iterator to the next element.
Thus, you will not be able to get the previous element.
Further, when there are no elements left to iterate, thennext()
throws ajava.util.NoSuchElementException
and therefore you can not use it to check for a terminating condition. - Method 4 uses
forEach
method ofjava.util.Iterable
interface. This is adefault
method added in this interface since java8. - Methods 4 and 5 may only be used when you are using java 8 for development.
- Method 5 utilizes
java.util.stream.Stream
to iterate over a collection and is a powerful feature introduced in java 8.
Using streams we may completely cut down iteration code when an element meeting a certain condition is required out of collection.
For Example, from an employee list, if I need to get an employee with a particular id. To know how, check this out.
Click the clap below if you liked the article.