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

In Java, LinkedHashMap is a powerful tool for maintaining key-value pairs while preserving the order of insertion. One common requirement is to access the first or last entry in a LinkedHashMap.

In this tutorial, we’ll explore various approaches to achieving this.

2. Preparing a LinkedHashMap Example

Before diving into the implementation for accessing the first and last entries in a LinkedHashMap, let’s briefly review the characteristics of LinkedHashMap.

First, LinkedHashMap is a part of the Java Collections Framework and extends the HashMap class. Furthermore, unlike a regular HashMap, a LinkedHashMap maintains the order of elements in the order in which they were inserted.

Depending on the constructor we use, this order can be either the insertion order or the access order. Simply put, the insertion order means that the elements are ordered according to when they’re added to the LinkedHashMap, while the access order implies that the elements are ordered by the frequency of access, with the most recently accessed elements appearing last.

In this tutorial, we’ll take an insertion-order LinkedHashMap as an example to demonstrate how to obtain the first and the last entries. But, the solutions work for access-order LinkedHashMaps too.

So, next, let’s prepare a LinkedHashMap object example:

static final LinkedHashMap<String, String> THE_MAP = new LinkedHashMap<>();

static {
    THE_MAP.put("key one", "a1 b1 c1");
    THE_MAP.put("key two", "a2 b2 c2");
    THE_MAP.put("key three", "a3 b3 c3");
    THE_MAP.put("key four", "a4 b4 c4");
}

As the example above shows, we used a static block to initialize the THE_MAP object.

For simplicity, in this tutorial, we assume the LinkedHashMap object isn’t null or empty. Also, we’ll leverage unit test assertions to verify whether each approach produces the expected result.

3. Iterating Through Map Entries

We know that Map‘s entrySet() method returns all entries in a Set backed by the map. Furthermore, for a LinkedHashMap, the entries in the returned Set follow the entries order in the map object.

Therefore, we can easily access any entry in a LinkedHashMap by iterating entrySet()‘s result through an Iterator. For example, linkedHashMap.entrySet().iterator().next() returns the first element in the map:

Entry<String, String> firstEntry = THE_MAP.entrySet().iterator().next();
assertEquals("key one", firstEntry.getKey());
assertEquals("a1 b1 c1", firstEntry.getValue());

However, obtaining the last entry isn’t as simple as how we retrieve the first entry. We must iterate to the last element in the Set to get the last map entry:

Entry<String, String> lastEntry = null;
Iterator<Entry<String,String>> it = THE_MAP.entrySet().iterator();
while (it.hasNext()) {
    lastEntry = it.next();
}

assertNotNull(lastEntry);
assertEquals("key four", lastEntry.getKey());
assertEquals("a4 b4 c4", lastEntry.getValue());

In this example, we iterate through the LinkedHashMap using an Iterator object and keep updating the lastEntry variable until we reach the last entry.

Our examples show this approach does the job for an insertion-order LinkedHashMaps. Some may ask if this approach works for access-order LinkedHashMap, too, since access entries in access-order LinkedHashMap may change their order.

Therefore, it’s worth noting that iterating over a view of the map won’t affect the order of iteration of the backing map. This is because only explicit access operations on the map will affect the order, such as map.get(key). So, this approach works for access-order LinkedHashMap as well.

4. Converting Map Entries to an Array

We know that arrays are pretty performant for random access. So, if we can convert the LinkedHashMap entries to an array, we can efficiently access the array’s first and last elements of the array.

We’ve learned we can get all map entries in a Set by calling entrySet(). Thus, Java Collection‘s toArray() method helps us to obtain an array from the Set:

Entry<String, String>[] theArray = new Entry[THE_MAP.size()];
THE_MAP.entrySet().toArray(theArray);

Then, accessing the first and the last elements from the array isn’t a challenge for us:

Entry<String, String> firstEntry = theArray[0];
assertEquals("key one", firstEntry.getKey());
assertEquals("a1 b1 c1", firstEntry.getValue());

Entry<String, String> lastEntry = theArray[THE_MAP.size() - 1];
assertEquals("key four", lastEntry.getKey());
assertEquals("a4 b4 c4", lastEntry.getValue());

5. Using Stream API

Stream API has been introduced since Java 8. It provides a series of convenient methods that allow us to handle collections easily.

Next, let’s see how to get the first entry from a LinkedHashMap using Java Streams:

Entry<String, String> firstEntry = THE_MAP.entrySet().stream().findFirst().get();
assertEquals("key one", firstEntry.getKey());
assertEquals("a1 b1 c1", firstEntry.getValue());

As we can see, we called the stream() method on the entrySet() result to get the map entries’ stream object. Then, findFirst() gives us the first element from the stream. It’s worth noting that the findFirst() method returns an Optional object. Since we knew the map wouldn’t be empty, we called the get() method directly to retrieve the map entry from the Optional object.

There are various ways to get the last element from a Stream instance. For example, we can use the skip() function to solve the problem:

Entry<String, String> lastEntry = THE_MAP.entrySet().stream().skip(THE_MAP.size() - 1).findFirst().get();

assertNotNull(lastEntry);
assertEquals("key four", lastEntry.getKey());
assertEquals("a4 b4 c4", lastEntry.getValue());

The skip() method accepts an int parameter. As its name implies, skip(n) returns a stream discarding the first n elements in the original stream. Therefore, we passed THE_MAP.size() – 1 to the skip() method to obtain a stream only containing the last element, which is THE_MAP‘s last entry.

6. Using Reflection API

Until now (Java 21), LinkedHashMap‘s implementation maintains a doubly linked list to hold key-value entries. Also, the head and the tail variables reference the map’s first and last entries:

/**
 * The head (eldest) of the doubly linked list.
 */
transient LinkedHashMap.Entry<K,V> head;

/**
 * The tail (youngest) of the doubly linked list.
 */
transient LinkedHashMap.Entry<K,V> tail;

Therefore, we can simply read these two variables to get the required entries. However, head and tail aren’t public variables. So, we cannot directly access them outside the java.util package.

Fortunately, we have a powerful weapon: Java Reflection API, which allows us to read or write to runtime attributes of classes. For example, we can read the head and the tail fields using reflection to get the map’s first and last entries:

Field head = THE_MAP.getClass().getDeclaredField("head");
head.setAccessible(true);
Entry<String, String> firstEntry = (Entry<String, String>) head.get(THE_MAP);
assertEquals("key one", firstEntry.getKey());
assertEquals("a1 b1 c1", firstEntry.getValue());

Field tail = THE_MAP.getClass().getDeclaredField("tail");
tail.setAccessible(true);
Entry<String, String> lastEntry = (Entry<String, String>) tail.get(THE_MAP);
assertEquals("key four", lastEntry.getKey());
assertEquals("a4 b4 c4", lastEntry.getValue());

We should note that when we run the test above with Java version 9 or later, the test fails with the following error message:

java.lang.reflect.InaccessibleObjectException: Unable to make field transient java.util.LinkedHashMap$Entry 
java.util.LinkedHashMap.head accessible: module java.base does not "opens java.util" to unnamed module ....

This is because, since version 9, Java has introduced the modular system, which limits the Reflection API reasonably.

To resolve the reflection illegal access problem, we can add “–add-opens java.base/java.util=ALL-UNNAMED” to the Java command line. As we use Apache Maven as the build tool, we can add this option to the surefire-plugin configuration to ensure the test using reflection runs smoothly with “mvn test“:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <argLine>
                    --add-opens java.base/java.util=ALL-UNNAMED
                </argLine>
            </configuration>
        </plugin>
    </plugins>
</build>

Additionally, it’s essential to remember that this method hinges on the presence of the “head” and “tail” fields within the LinkedHashMap implementation. In case of potential alterations in Java’s future releases, such as removing or renaming these fields, this solution may no longer be effective.

7. Conclusion

In this article, we initiated our exploration by briefly understanding the key features of a LinkedHashMap. Then, we delved into practical examples to illustrate various methods for retrieving the first and last key-value pairs from a LinkedHashMap.

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)