How an iterate object can be used to iterate a list in Java?

How to Iterate List in Java

In Java, List is is an interface of the Collection framework. It provides us to maintain the ordered collection of objects. The implementation classes of List interface are ArrayList, LinkedList, Stack, and Vector. The ArrayList and LinkedList are widely used in Java. In this section, we will learn how to iterate a List in Java. Throughout this section, we will use ArrayList.

Java for Loop

  1. Basic for Loop
  2. Enhanced for Loop

Java Iterators

  1. Iterator
  2. ListIterator

Java forEach Method

  1. Iterable.forEach()
  2. Stream.forEach()

1. Introduction

Iterating over the elements of a list is one of the most common tasks in a program.

In this tutorial, we're going to review different ways to do this in Java. We'll be focusing on iterating through the list in order, though going in reverseis simple, too.

How to iterate over a Java list?

Java 8Object Oriented ProgrammingProgramming

Often, you will want to cycle through the elements in a collection. For example, you might want to display each element.

The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.

Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list and the modification of elements.

Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator() method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.

In general, to use an iterator to cycle through the contents of a collection, follow these steps −

  1. Obtain an iterator to the start of the collection by calling the collection's iterator() method.
  2. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
  3. Within the loop, obtain each element by calling next().

1. Iterate ArrayList with ‘for loop’

Java program to iterate through an ArrayList of objects using the standard for loop.

ArrayList namesList = new ArrayList(Arrays.asList( "alex", "brian", "charles") ); for(int i = 0; i < namesList.size(); i++) { System.out.println(namesList.get(i)); }

2. Iterate ArrayList with ‘for-each loop’

Java program to iterate through an ArrayList of objects using for-each loop.

ArrayList namesList = new ArrayList(Arrays.asList( "alex", "brian", "charles") ); for(String name : namesList) { System.out.println(name); }

3 Examples of looping through a List in Java

Here is a sample Java program that demonstrates How to loop through aList in Java in three different ways, Iterator, for-each loop, and traditional for loop. This technique can be used to loop throughArrayList or any other index-based List implementation like Vector.

The other two methods like Iterator and enhanced for loop can be used along with any Collection class like HashSet, TreeSet, LinkedHashSet, etc. They are actually the standard way to iterate through the collection in Java.


How an iterate object can be used to iterate a list in Java?


The traditional for loop approach is only possible and efficient because of the index-based nature of the List interface, but if you use this with a linked list then you will get worse performance because in LinkedListaccessing an element with an index is O(n) operation rather than O(1) operation. This is also the fundamental difference between an ArrayList and LinkedList in Java.

The new method of iterating over a list using the forEach() method is only available in Java SE 8 and I recommend you to read this article to learn how to loop through a list using the forEach()method in Java 8 before you start using them.


Btw, Java SE 8 is full of exciting and more powerful features and it's essential for a Java developer to learn those features, given it's the most popular Java version. If you are interested, you should follow a good Java 8 course likeWhat's New in Java 8 on Pluralsight to learn quickly.

How an iterate object can be used to iterate a list in Java?



Alternatively, you can always choose the one from this list of good Java 8 books, earlier published by me.




How to loop over a List in Java

Here is our complete Java program to show you all three ways to loop over a list in Java. You can use these methods to loop over any List like ArrayList, LinkedList, or even Vector in Java.

package example;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
*
* Java program to demonstrate different ways to loop,
* iterate or traverse List in Java.
* There are three examples in this program,
* first examples show how to loop List
* using Iterator, Second Example shows Looping over List
* using advanced Java 5 for loop
* while third and last examples demonstrate
* use of traditional for loop for traversing over
* a List in Java.
*
* @author Javin Paul
*/

public class ListLoopExample{

public static void main(String args[]){

//First example to iterate List in Java using Iterator
List<String> languages = Arrays.asList("Java",
"C++", "Scala", "Groovy");


//Getting Iterator from List in Java
Iterator<String> iterator = languages.iterator();
System.out.println("Iterating List in Java
using Iterator "
);


//Iterating through all elements of List
while (iterator.hasNext()) {
System.out.printf("Current element in List
is %s %n"
, iterator.next());
}


//Second example of Iterating over List in Java
// using a foreach loop

System.out.println("Looping List in Java using a
foreach loop"
);
for (String city : languages) {
System.out.println("List Element: " + city);
}

//Third example of Looping List using traditional for loop
for(int i =0; i<languages.size(); i++){
System.out.printf("programming language #%d in
List is : %s %n"
, i, languages.get(i) );
}


}
}

Output:
Iterating List in Java using Iterator
The current element in List is London
The current element in List is Tokyo
The current element in List is NewYork
The current element in List in Mumbai
Looping List in Java using a foreach loop
List Element: London
List Element: Tokyo
List Element: NewYork
List Element: Mumbai
City #0 in List is: London
City #1 in List is: Tokyo
City #2 in List is: NewYork
City #3 in List is: Mumbai


How an iterate object can be used to iterate a list in Java?
That’s all on How to iterate or loop over aList in Java. In this Java tutorial, we have seen an example of all three ways of looping List in Java. the first example demonstrates the use of Iterator with List, the second use for loop for looping over List, and the third example uses traditional old for a loop. All this technique can be applied to any index-based List implementation including ArrayList and Vector in Java.

Further Learning
TheComplete Java Masterclass
Java Fundamentals: Collections
Java Programming Interview Exposed by Markham


Other Java Collection Articlesyou may like
  • How to sort a Map by keys and values in Java? (tutorial)
  • Top 10 Courses to learn Java for Beginners (best courses)
  • How to sort an ArrayList in ascending and descending order in Java? (tutorial)
  • Difference between ArrayList and HashSet in Java? (answer)
  • Top 5 Courses to learn Java Collections and Stream (courses)
  • What is the difference between TreeMap and TreeSet in Java? (answer)
  • Top 10 courses to learn Python in 2020 (courses)
  • The difference between HashSet and TreeSet in Java? (answer)
  • 7 Best Courses to learn Data STructure and Algorithms (best courses)
  • 10 Free courses to learn Java in-depth (courses)
  • The difference between HashMap and ConcurrentHashMap in Java? (answer)
  • 10 courses to learn Data Structure in-depth (courses)
  • The difference between HashMap and LinkedHashMap in Java? (answer)
  • 20+ basic algorithms interview questions for programmers (questions)
  • Top 5 Courses to become full-stack Java developer (courses)
  • The difference between Hashtable and HashMap in Java? (answer)
  • 50+ Core Java Interview Questions and Answers (questions)
  • The difference between ArrayList and LinkedList in Java? (answer)
  • Top 5 Courses to learn Spring Framework in-depth (courses)
  • The difference between Vector and ArrayList in Java? (answer)

Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. -If you are keen to learn Java Programming in-depth but looking for free online courses then you can also check outJava Tutorial for Complete Beginners (FREE)course on Udemy. It's completely free and you just need an Udemy account to join this course.