eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

When we work with collections, we often need to iterate through their elements. Java provides two essential interfaces for this purpose: Iterator and ListIterator. Though they serve a similar purpose, there are crucial distinctions between the two that we must understand.

In this tutorial, we’ll explore the differences between Iterator and ListIterator in Java.

2. The Iterator Interface

The standard Collection interface extends Iterable. Further, the Iterable interface defines the iterator() method to return an Iterator instance:

public interface Iterable<T> {
    Iterator<T> iterator();
    ...
}

Therefore, Iterator is a fundamental part of the Java Collections Framework and available for all Collection implementations, such as List and Set. It allows us to access elements in a collection sequentially without knowing its underlying structure.

It offers three primary methods, hasNext(), next(), and remove():

public interface Iterator<E> {
    
    boolean hasNext();
    E next();   
    default void remove() { throw new UnsupportedOperationException("remove"); }
    ...
}

Using the hasNext() and the next() methods, we can check if there are more elements and move to those elements.

However, the remove() method removes from the collection the last element returned by the next() method. Further, as we can see, the remove() method is a default method, so it’s optional. Its implementation depends on the underlying collection.

Let’s create a unit test to cover the basic usage of Iterator‘sthree primary methods:

List<String> inputList = Lists.newArrayList("1", "2", "3", "4", "5");
Iterator<String> it = inputList.iterator();
while (it.hasNext()) {
    String e = it.next();
    if ("3".equals(e) || "5".equals(e)) {
        it.remove();
    }
}

assertEquals(Lists.newArrayList("1", "2", "4"), inputList);

It’s worth noting that we can traverse collection only in the forward direction using an Iterator.

3. The ListIterator Interface

The ListIterator is a subtype of Iterator. Therefore, all the features Iterator offers are also available in ListIterator:

public interface ListIterator<E> extends Iterator<E> {
   
    boolean hasNext();
    E next();
    void remove();

    boolean hasPrevious();
    E previous();
    int nextIndex();
    int previousIndex();
    void set(E e);
    void add(E e);
}

As its name implies, ListItrator is used explicitly with lists. Apart from the three methods from the Iterator interface (hasNext(), next(), and remove()), the ListIterator interface has a set of new methods, such as previous(), set(), add(), etc.

Next, we’ll take a closer look at these new methods and understand the difference between Iterator and ListIterator.

For simplicity, we’ll use ArrayList as an example to understand the usage of ListIterator.

3.1. Forward and Backward Iterating Elements

ListIterator allows us to traverse a list in both forward and backward directions. Before we see how to do that, let’s understand ListIterator‘s cursor positions.

Simply put, ListIterator‘s cursor doesn’t point to an element directly. Given a list with n elements, ListIterator has the following n+1 possible cursor positions (^):

Elements:            Element_0    Element_1    Element_2    Element_3  ... Element_(n-1)
Cursor positions:  ^            ^            ^            ^           ^    ...           ^

ListIterator’s previous() and next() methods return the element before and after the current cursor position. Therefore, we should note that alternating calls to next() and previous() return the same element repeatedly. Understanding this characteristic is essential in order to implement bidirectional traversing using ListIterator.

So, let’s see this behavior through an example:

List<String> inputList = Lists.newArrayList("1", "2", "3", "4", "5");
ListIterator<String> lit = inputList.listIterator(); // ^ 1 2 3 4 5
lit.next(); // 1 ^ 2 3 4 5
lit.next(); // 1 2 ^ 3 4 5
 
for (int i = 1; i <= 100; i++) {
    assertEquals("2", lit.previous());
    assertEquals("2", lit.next());
}

As the code above shows, after calling the next() method twice, the cursor is located between “2” and “3”. Then, we repeated the previous() and next() calls 100 times. That is to say, it performed next() -> previous() -> next() -> previous() -> … 100 times. As we noted earlier, we’ll get the same element every time we alternate to next() and previous(). In this case, it’s “2”. We verified this with two assertions up there.

So next, let’s see how to access list elements in both directions using ListIterator:

List<String> inputList = Lists.newArrayList("1", "2", "3", "4", "5");
ListIterator<String> lit = inputList.listIterator(); // ^ 1 2 3 4 5

assertFalse(lit.hasPrevious()); // lit is at the beginning of the list
assertEquals(-1, lit.previousIndex());

// forward
assertEquals("1", lit.next()); // after next(): 1 ^ 2 3 4 5
assertEquals("2", lit.next()); // after next(): 1 2 ^ 3 4 5
assertEquals("3", lit.next()); // after next(): 1 2 3 ^ 4 5

// backward
assertTrue(lit.hasPrevious());
assertEquals(2, lit.previousIndex());
assertEquals("3", lit.previous()); // after previous(): 1 2 ^ 3 4 5

assertTrue(lit.hasPrevious());
assertEquals(1, lit.previousIndex());
assertEquals("2", lit.previous()); // after previous(): 1 ^ 2 3 4 5

assertTrue(lit.hasPrevious());
assertEquals(0, lit.previousIndex());
assertEquals("1", lit.previous()); // after previous(): ^ 1 2 3 4 5

As the example above shows, we first used next() calls forwardly accessed the first three elements in the list. Then, we got these elements in the backward direction using previous() calls.

We’ve also used previousIndex() in the code above. ListIterator’s previousIndex() returns the index of the element that would be returned by the next call to the previous() method. Similarly, nextIndex() tells the index of the element that would be returned by a call to next().

3.2. The set() Method

ListIterator offers us the set() method to set an element’s value. The Iterator interface doesn’t support this feature. However, we should note that ListIterator.set() sets the last element from the next() or previous() call:

List<String> inputList = Lists.newArrayList("1", "2", "3", "4", "5");
ListIterator<String> lit = inputList.listIterator(1); // ^ 1 2 3 4 5
lit.next(); // 1 ^ 2 3 4 5
assertEquals("3", lit.next()); // 1 2 ^ 3 4 5

lit.set("X");
assertEquals(Lists.newArrayList("1", "2", "X", "4", "5"), inputList);

assertEquals("X", lit.previous()); // 1 2 ^ X 4 5

assertEquals("2", lit.previous()); // 1 ^ 2 X 4 5
lit.set("Y");
assertEquals(Lists.newArrayList("1", "Y", "X", "4", "5"), inputList);

As the test above shows, when we called set(), the element returned by the last next() or previous() call got replaced by the new value.

3.3. The add() Method

ListIterator allows us to add() elements at the current cursor position following this rule:

           
Element_x (New)   ^     Element_Y
           |
           ^
           |____ add(New) 

Calling add(NEW) inserts an element before the current cursor position so that a subsequent next() call won’t be affected, and a subsequent previous() returns the new element.

An example can make this clear:

List<String> inputList = Lists.newArrayList("1", "2", "3", "4", "5");
ListIterator<String> lit = inputList.listIterator(); // ^ 1 2 3 4 5
lit.next(); // 1 ^ 2 3 4 5
lit.next(); // 1 2 ^ 3 4 5
lit.next(); // 1 2 3 ^ 4 5

lit.add("X"); // 1 2 3 X ^ 4 5
assertEquals("4", lit.next()); // 1 2 3 X 4 ^ 5; next() isn't affected

lit.previous(); // 1 2 3 X ^ 4 5
lit.previous(); // 1 2 3 ^ X 4 5
lit.previous(); // 1 2 ^ 3 X 4 5
lit.add("Y");   // 1 2 Y ^ 3 X 4 5

assertEquals("Y", lit.previous()); // previous() always return the new element

assertEquals(Lists.newArrayList("1", "2", "Y", "3", "X", "4", "5"), inputList);

4. Conclusion

In this article, we’ve discussed the usage of Iterator and ListIterator. Now, let’s summarize the key differences between them:

  • Iterator is a universal interface used to traverse any collection, while ListIterator is specific to lists and provides bidirectional iteration.
  • Iterator supports only forward iteration with next(). On the other hand, ListIterator supports both forward and backward iteration with next() and previous().
  • ListIterator includes additional methods like add() and set() to insert or replace a list element, while the Iterator interface doesn’t have these features.
The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)