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 working with arrays in Java, there are situations where we need to identify whether the current element in an iteration is the last one.

In this tutorial, let’s explore a few common ways to achieve this, each with its advantages depending on the context of our application.

2. Introduction to the Problem

As usual, let’s understand the problem through examples. For example, let’s say we have an array:

String[] simpleArray = { "aa", "bb", "cc" };

Some might think the last element determination while iteration is a simple problem since we can always compare the current element to the last element (array[array.length – 1]). Yes, this approach works for arrays like simpleArray.

However, once the array contains duplicate elements, this approach won’t work anymore, for instance:

static final String[] MY_ARRAY = { "aa", "bb", "cc", "aa", "bb", "cc"};

Now, the last element is “cc”. But we have two “cc” elements in the array. Therefore, checking if the current element equals the last element can result in the wrong result.

So, we need a stable solution to check whether the current element is the last one while iterating an array.

In this tutorial, we’ll address solutions for different iteration scenarios. Also, to demonstrate each approach easily, let’s take MY_ARRAY as the input and use iteration to build this result String:

static final String EXPECTED_RESULT = "aa->bb->cc->aa->bb->cc[END]";

Of course, various ways exist to join array elements into a String with separators. However, our focus is to showcase how to determine if we’ve reached the last iteration. 

Additionally, we shouldn’t forget Java has object arrays and primitive arrays. We’ll also cover primitive array scenarios.

3. Checking the Indexes in Loops

A straightforward method to check if an element is the last in an array is to use a traditional index-based for loop. This approach gives us direct access to each element’s index, which can be compared to the last element’s index in the array to determine if we’re at the last element:

int lastIndex = MY_ARRAY.length - 1;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < MY_ARRAY.length; i++) {
    sb.append(MY_ARRAY[i]);
    if (i == lastIndex) {
        sb.append("[END]");
    } else {
        sb.append("->");
    }
}
assertEquals(EXPECTED_RESULT, sb.toString());

In this example, we first get the last element’s index (lastIndex) in the array. We compare the loop variable i to lastIndex on each iteration to determine if we’ve reached the last element. Then, we can choose the corresponding separator.

Since this approach checks array indexes, it works for object and primitive arrays.

4. Using For-Each Loop with an External Counter

Sometimes, we prefer using a for-each loop, for its simplicity and readability. However, it doesn’t provide direct access to the index. But we can create an external counter to keep track of our position in the array:

int counter = 0;
StringBuilder sb = new StringBuilder();
for (String element : MY_ARRAY) {
    sb.append(element);
    if (++counter == MY_ARRAY.length) {
        sb.append("[END]");
    } else {
        sb.append("->");
    }
}
assertEquals(EXPECTED_RESULT, sb.toString());

In this example, we manually maintain a counter variable that starts at 0 and increments with each iteration. We also check if the counter has reached the given array’s length on each iteration.

The external counter approach works similarly to the index-based for loop. Therefore, it also works for primitive arrays.

5. Converting the Array to an Iterable

Java’s Iterator allows us to iterate data collections conveniently. Furthermore, it provides the hasNext() method, which is ideal to check if the current element is the last one in the collection.

However, arrays don’t implement the Iterable interface in Java. We know Iterator is available in Iterable or Stream instances. Therefore, we can convert the array to an Iterable or Stream to obtain an Iterator.

5.1. Object Arrays

List implements the Iterable interface. So, let’s can convert an object array to a List and get its Iterator:

Iterator<String> it = Arrays.asList(MY_ARRAY).iterator();
StringBuilder sb = new StringBuilder();
while (it.hasNext()) {
    sb.append(it.next());
    if (it.hasNext()) {
        sb.append("[END]");
    } else {
        sb.append("->");
    }
}
assertEquals(EXPECTED_RESULT, sb.toString());

In this example, we use Arrays.asList() to convert our String array to a List<String>.

Alternatively, we can leverage the Stream API to convert an object array to a Stream and obtain an Iterator:

Iterator<String> it = Arrays.stream(MY_ARRAY).iterator();
StringBuilder sb = new StringBuilder();
while (it.hasNext()) {
    sb.append(it.next());
    if (it.hasNext()) {
        sb.append("[END]");
    } else {
        sb.append("->");
    }
}
assertEquals(EXPECTED_RESULT, sb.toString());

As the code above shows, we use Arrays.stream() to get a Stream<String> from the input String array.

5.2. Primitive Arrays

Let’s first create an int[] array as an example and the expected String result:

static final int[] INT_ARRAY = { 1, 2, 3, 1, 2, 3 };
static final String EXPECTED_INT_ARRAY_RESULT = "1->2->3->1->2->3[END]";

Stream API offers three commonly used primitive types of streams: IntStream, LongStream, and DoubleStream. So, if we want to use an Iterator to iterate an int[], long[], or double[], we can easily convert the primitive array to a Stream, for example:

Iterator<Integer> it = IntStream.of(INT_ARRAY).iterator();
StringBuilder sb = new StringBuilder();
while (it.hasNext()) {
    sb.append(it.next());
    if (it.hasNext()) {
        sb.append("[END]");
    } else {
        sb.append("->");
    }
}
assertEquals(EXPECTED_INT_ARRAY_RESULT, sb.toString());

Alternatively, we can still use Arrays.stream() to get a primitive type Stream from an int[], long[], or double[]:

public static IntStream stream(int[] array)
public static LongStream stream(long[] array)
public static DoubleStream stream(double[] array)

If our primitive array isn’t one of int[], long[], or double[], we can convert it to a List of its wrapper type, for example, converting a char[] to a List<Character>. Then, we can use an Iterator to iterate the List.

However, when we perform the primitive array to List conversion, we must walk through the array. Thus, we iterate the array to obtain the List and then iterate the List again for the actual work. Therefore, it’s not an optimal approach to convert a primitive array to a List just for using an Iterator to iterate it. 

Next, let’s see how we can use an Iterator to iterate primitive arrays other than int[], long[], or double[].

6. Creating a Custom Iterator

We’ve seen that it’s handy to iterate an array and determine the last iteration using an Iterator. Also, we’ve discussed that obtaining an Iterator of a primitive array by converting the array to List isn’t an optimal approach. Instead, we can implement a custom Iterator for primitive arrays to gain Iterator‘s benefits without creating intermediate List or Stream objects.

First, let’s prepare a char[] array as our input and the expected String result:

static final char[] CHAR_ARRAY = { 'a', 'b', 'c', 'a', 'b', 'c' };
static final String EXPECTED_CHAR_ARRAY_RESULT = "a->b->c->a->b->c[END]";

Next, let’s create a custom Iterator for char[] arrays:

class CharArrayIterator implements Iterator<Character> {
    private final char[] theArray;
    private int currentIndex = 0;

    public static CharArrayIterator of(char[] array) {
        return new CharArrayIterator(array);
    }

    private CharArrayIterator(char[] array) {
        theArray = array;
    }

    @Override
    public boolean hasNext() {
        return currentIndex < theArray.length;
    }

    @Override
    public Character next() {
        return theArray[currentIndex++];
    }
}

As the code shows, the CharArrayIterator class implements the Iterator interface. It holds the char[] array as an internal variable. Next to the array variable, we define currentIndex to track the current index position. It’s worth mentioning that autoboxing (char -> Character) happens in the next() method.

Next, let’s see how to use our CharArrayIterator:

Iterator<Character> it = CharArrayIterator.of(CHAR_ARRAY);
StringBuilder sb = new StringBuilder();
while (it.hasNext()) {
    sb.append(it.next());
    if (it.hasNext()) {
        sb.append("->");
    } else {
        sb.append("[END]");
    }
}
assertEquals(EXPECTED_CHAR_ARRAY_RESULT, sb.toString());

If we need custom Iterators for other primitive arrays, we must create similar classes.

7. Conclusion

In this article, we’ve explored how to determine if an element is the last one while iterating over an array in different iteration scenarios. We’ve also discussed the solutions for both object and primitive array cases.

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)