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. Introduction

Iterating is a cornerstone of programming, enabling developers to traverse and easily manipulate data structures. However, there are situations where we may need to iterate over these collections while skipping the first element. In this tutorial, we’ll explore various methods to skip the first element using loops and the Stream API.

2. Skipping the First Element

There are various ways to skip the first element in Java when iterating through a collection. Below, we cover three major approaches: using standard loops, using the Iterator interface, and utilizing the Stream API.

Some algorithms require skipping the first element for different reasons: to process it separately or skip it entirely, for example, CSV headers. Calculating running differences between the daily income of a small business might be a good example of this approach:

Skipping the First Element Example

Iterating from the second element helps us to create a simple algorithm and saves us from unnecessary and non-intuitive checks.

2.1. For Loop

The simplest way to skip the first element is to use a for loop and start the counter variable from 1 instead of 0. This approach is most suitable for collections that support indexed access, like ArrayList and simple arrays:

void skippingFirstElementInListWithForLoop(List<String> stringList) {
    for (int i = 1; i < stringList.size(); i++) {
        process(stringList.get(i));
    }
} 

The main benefit of this approach is its simplicity. Also, it allows us to access the first value if we would like to do so. At the same time, setting the initial value might be easily overlooked.

2.2. While Loop

Another way is to use a while loop along with an Iterator. We can manually advance the iterator to skip the first element:

void skippingFirstElementInListWithWhileLoop(List<String> stringList) {
    Iterator<String> iterator = stringList.iterator();
    if (iterator.hasNext()) {
        iterator.next();
    }
    while (iterator.hasNext()) {
        process(iterator.next());
    }
}

One of the benefits of this method is the fact that it works with all the Iterable collections, such as Set:

void skippingFirstElementInSetWithWhileLoop(Set<String> stringSet) {
    Iterator<String> iterator = stringSet.iterator();
    if (iterator.hasNext()) {
        iterator.next();
    }
    while (iterator.hasNext()) {
        process(iterator.next());
    }
}

An additional benefit is that we can abstract the collection to the most general class; in this case, it would be Iterable and reuse the code. However, as Sets, in most cases, don’t have the notion of order, it’s not clear which element we’ll skip. On the other side, if we need the first element, we have to store it explicitly:

void skippingFirstElementInListWithWhileLoopStoringFirstElement(List<String> stringList) {
    Iterator<String> iterator = stringList.iterator();
    String firstElement = null;
    if (iterator.hasNext()) {
        firstElement = iterator.next();
    }
    while (iterator.hasNext()) {
        process(iterator.next());
        // additional logic using fistElement
    }
}

2.3. Stream API

Java 8 introduced the Stream API, which provides a more declarative way to manipulate collections. To skip the first element, we can use the skip() method:

void skippingFirstElementInListWithStreamSkip(List<String> stringList) {
    stringList.stream().skip(1).forEach(this::process);
}

Like the previous one, this method works on Iterable collection and is quite verbose about its intentions. We can easily use Set with this approach:

void skippingFirstElementInSetWithStreamSkip(Set<String> stringSet) {
    stringSet.stream().skip(1).forEach(this::process);
}

Also, we can use a Map:

void skippingFirstElementInMapWithStreamSkip(Map<String, String> stringMap) {
    stringMap.entrySet().stream().skip(1).forEach(this::process);
}

Maps, similar to Sets, don’t maintain the order of the elements, so please use this with caution, as the first element isn’t clearly defined in this case. However, sometimes skipping an element in a Set or in a Map might be useful.

2.4. Using subList()

Another way to skip the first element in Lists is using the subList() method. This method returns a view of the portion of the list between the specified fromIndex, inclusive, and toIndex, exclusive. When we pair this with a for-each loop, we can easily skip the first element:

void skippingFirstElementInListWithSubList(List<String> stringList) {
    for (final String element : stringList.subList(1, stringList.size())) {
        process(element);
    }
}

One of the issues is that subList() can fail on empty lists. Another thing is that it’s not clear, especially for people new to Java, that it doesn’t create a separate collection and provides a view of the original one. Overall, this is a highly imperative way of iterating.

2.5. Other Methods

Although there are only a handful of fundamental ways to iterate over a collection, we could combine and alter them to get more variations. As these variations aren’t substantially different, we list them here to show possible approaches and inspire experimentation.

We can skip the first element using a for loop with an additional if statement. It’s useful when we need to process the first element separately from the others:

void skippingFirstElementInListWithForLoopWithAdditionalCheck(List<String> stringList) {
    for (int i = 0; i < stringList.size(); i++) {
        if (i == 0) {
            // do something else
        } else {
            process(stringList.get(i));
        }
    }
}

We can apply the logic we’re using in a for loop to a while loop and use a counter inside it:

void skippingFirstElementInListWithWhileLoopWithCounter(List<String> stringList) {
    int counter = 0;
    while (counter < stringList.size()) {
        if (counter != 0) {
            process(stringList.get(counter));
        }
        ++counter;
    }
}

This approach might be helpful when we need to advance the list in different steps depending on some internal logic.

Also, we can combine the approach with subList and with stream:

void skippingFirstElementInListWithStreamSkipAndSubList(List<String> stringList) {
    stringList.subList(1, stringList.size()).forEach(this::process);
}

Overall, our imagination can bring us to some esoteric decisions that should not be used at all:

void skippingFirstElementInListWithReduce(List<String> stringList) {
    stringList.stream().reduce((skip, element) -> {
        process(element);
        return element;
    });
}

3. Conclusion

While Java offers different ways to iterate a collection while skipping the first element, the primary metric in picking the right approach is the clarity of the code. Thus, we should opt for two simple and the most verbose methods, which are simple for loop or stream.skip(). Other methods are more complex, contain more moving parts, and should be avoided if possible.

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)