Skip to content
Fix Code Error

Ways to iterate over a list in Java

March 13, 2021 by Code Error
Posted By: Anonymous

Being somewhat new to the Java language I’m trying to familiarize myself with all the ways (or at least the non-pathological ones) that one might iterate through a list (or perhaps other collections) and the advantages or disadvantages of each.

Given a List<E> list object, I know of the following ways to loop through all elements:

Basic for loop (of course, there’re equivalent while / do while loops as well)

// Not recommended (see below)!
for (int i = 0; i < list.size(); i++) {
    E element = list.get(i);
    // 1 - can call methods of element
    // 2 - can use 'i' to make index-based calls to methods of list

    // ...
}

Note: As @amarseillan pointed out, this form is a poor choice
for iterating over Lists, because the actual implementation of
the get method may not be as efficient as when using an Iterator.
For example, LinkedList implementations must traverse all of
the elements preceding i to get the i-th element.

In the above example there’s no way for the List implementation to
“save its place” to make future iterations more efficient.
For an ArrayList it doesn’t really matter, because the complexity/cost of get is constant time (O(1)) whereas for a LinkedList is it proportional to the size of the list (O(n)).

For more information about the computational complexity of the built-in Collections implementations, check out this question.

Enhanced for loop (nicely explained in this question)

for (E element : list) {
    // 1 - can call methods of element

    // ...
}

Iterator

for (Iterator<E> iter = list.iterator(); iter.hasNext(); ) {
    E element = iter.next();
    // 1 - can call methods of element
    // 2 - can use iter.remove() to remove the current element from the list

    // ...
}

ListIterator

for (ListIterator<E> iter = list.listIterator(); iter.hasNext(); ) {
    E element = iter.next();
    // 1 - can call methods of element
    // 2 - can use iter.remove() to remove the current element from the list
    // 3 - can use iter.add(...) to insert a new element into the list
    //     between element and iter->next()
    // 4 - can use iter.set(...) to replace the current element

    // ...
}

Functional Java

list.stream().map(e -> e + 1); // Can apply a transformation function for e

Iterable.forEach, Stream.forEach, …

(A map method from Java 8’s Stream API (see @i_am_zero’s answer).)

In Java 8 collection classes that implement Iterable (for example, all Lists) now have a forEach method, which can be used instead of the for loop statement demonstrated above. (Here is another question that provides a good comparison.)

Arrays.asList(1,2,3,4).forEach(System.out::println);
// 1 - can call methods of an element
// 2 - would need reference to containing object to remove an item
//     (TODO: someone please confirm / deny this)
// 3 - functionally separates iteration from the action
//     being performed with each item.

Arrays.asList(1,2,3,4).stream().forEach(System.out::println);
// Same capabilities as above plus potentially greater
// utilization of parallelism
// (caution: consequently, order of execution is not guaranteed,
// see [Stream.forEachOrdered][stream-foreach-ordered] for more
// information about this).

What other ways are there, if any?

(BTW, my interest does not stem at all from a desire to optimize performance; I just want to know what forms are available to me as a developer.)

Solution

The three forms of looping are nearly identical. The enhanced for loop:

for (E element : list) {
    . . .
}

is, according to the Java Language Specification, identical in effect to the explicit use of an iterator with a traditional for loop. In the third case, you can only modify the list contents by removing the current element and, then, only if you do it through the remove method of the iterator itself. With index-based iteration, you are free to modify the list in any way. However, adding or removing elements that come before the current index risks having your loop skipping elements or processing the same element multiple times; you need to adjust the loop index properly when you make such changes.

In all cases, element is a reference to the actual list element. None of the iteration methods makes a copy of anything in the list. Changes to the internal state of element will always be seen in the internal state of the corresponding element on the list.

Essentially, there are only two ways to iterate over a list: by using an index or by using an iterator. The enhanced for loop is just a syntactic shortcut introduced in Java 5 to avoid the tedium of explicitly defining an iterator. For both styles, you can come up with essentially trivial variations using for, while or do while blocks, but they all boil down to the same thing (or, rather, two things).

EDIT: As @iX3 points out in a comment, you can use a ListIterator to set the current element of a list as you are iterating. You would need to use List#listIterator() instead of List#iterator() to initialize the loop variable (which, obviously, would have to be declared a ListIterator rather than an Iterator).

Answered By: Anonymous

Related Articles

  • What is the worst programming language you ever worked with?
  • Callback functions in C++
  • Examples of GoF Design Patterns in Java's core libraries
  • How can I resolve Web Component Testing error?
  • Best practice multi language website
  • Best way to replace multiple characters in a string?
  • Unable to run Robolectric and Espresso with a…
  • AppCompat v7 r21 returning error in values.xml?
  • Fastest way to iterate over all the chars in a String
  • Why is 2 * (i * i) faster than 2 * i * i in Java?
  • TLS 1.3 server socket with Java 11 and self-signed…
  • How does PHP 'foreach' actually work?
  • When I'm testing a web app by JUnit and Mockito I…
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • ClassNotFoundException:…
  • java IO Exception: Stream Closed
  • Jetpack Compose and Hilt Conflict
  • Eclipse will not start and I haven't changed anything
  • Adding gif image in an ImageView in android
  • Neither BindingResult nor plain target object for…
  • What does a "Cannot find symbol" or "Cannot resolve…
  • Reference — What does this symbol mean in PHP?
  • SecurityException: Permission denied (missing…
  • Gradle error: Execution failed for task…
  • For-each over an array in JavaScript
  • Is it possible to apply CSS to half of a character?
  • How to filter a RecyclerView with a SearchView
  • SQLException: No suitable Driver Found for…
  • Auto-fit TextView for Android
  • Why is it common to put CSRF prevention tokens in cookies?
  • data.table vs dplyr: can one do something well the…
  • problem with client server unix domain stream…
  • Show/hide 'div' using JavaScript
  • Why does C++ code for testing the Collatz conjecture…
  • Requested bean is currently in creation: Is there an…
  • Knight's tour Problem - storing the valid moves then…
  • Iterator Loop vs index loop
  • android studio 0.4.2: Gradle project sync failed error
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • How to loop through array in jQuery?
  • Android- Error:Execution failed for task…
  • Can't access Eclipse marketplace
  • Show scroll update when scrolling down page
  • Reference - What does this regex mean?
  • org.gradle.api.tasks.TaskExecutionException:…
  • Execution failed for task…
  • What are the undocumented features and limitations…
  • How do I use arrays in C++?
  • Undefined reference to 'vtable for ✘✘✘'
  • Using enums in a spring entity
  • Java Array, Finding Duplicates
  • Implementation of user defined array on stack and/or…
  • Replacing a 32-bit loop counter with 64-bit…
  • Getting Dropwizard Client And Jersey/HTTP I/O Error…
  • Android Studio 4.2.1 NullPointer Exception on startup
  • What are major differences between C# and Java?
  • Why is there no SortedList in Java?
  • Mock MQRFH2 header in JUnit Testing Error [MQRFH2…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • What is a NullReferenceException, and how do I fix it?
  • Smart way to truncate long strings
  • How to convert java.util.Date to java.sql.Date?
  • Why are elementwise additions much faster in…
  • C++ OpenGL stb_image.h errors
  • What's the best way to get the last element of an…
  • Drawing a simple line graph in Java
  • collision detection from picturebox in a list c#
  • How to parse JSON file with Spring
  • Ukkonen's suffix tree algorithm in plain English
  • Visual Studio debugging/loading very slow
  • How do I install Java on Mac OSX allowing version switching?
  • Could not install Gradle distribution from…
  • Configure hibernate to connect to database via JNDI…
  • Unresponsive hamburger icon in HTML
  • Do you (really) write exception safe code?
  • JPA Hibernate Persistence exception…
  • Vaadin Spring Boot - There was an exception while…
  • Single Page Application: advantages and disadvantages
  • SQL query return data from multiple tables
  • Text size and different android screen sizes
  • Draw in Canvas by finger, Android
  • "Non-resolvable parent POM: Could not transfer…
  • Polymer 1.0 'array-style' path accessors,…
  • Is it possible to print a variable's type in standard C++?
  • What is Ember RunLoop and how does it work?
  • Head pointer not accessible when creating a method…
  • How to add Typescript to a Nativescript-Vue project?
  • VueJs single file component not reading data/props/methods
  • Plugin…
  • SQL Server: Query fast, but slow from procedure
  • Builder pattern without inner class
  • How do I append one string to another in Python?
  • HTTP Status 500 - org.apache.jasper.JasperException:…
  • What is an IndexOutOfRangeException /…
  • Accessing a Shared File (UNC) From a Remote,…
  • The definitive guide to form-based website authentication
  • Can Python test the membership of multiple values in a list?
  • Trouble with qsort with key/value structs in a btree
  • Java Hashmap: How to get key from value?
  • ClassNotFoundException thrown

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Shell command to tar directory excluding certain files/folders

Next Post:

Check whether a string is not null and not empty

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error