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 – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Introduction

The LinkedHashMap class provides a convenient way to maintain the insertion order of key-value pairs while still offering the functionality of a HashMap.

In this tutorial, we’ll explore several approaches to retrieve the position (index) within a LinkedHashMap.

2. Overview of LinkedHashMap

LinkedHashMap is a Java class that extends HashMap and maintains a linked list of entries in the order they were inserted. This means that the order of elements in a LinkedHashMap is predictable and reflects the insertion order of keys.

To work with a LinkedHashMap, we can create an instance and populate it with key-value pairs. The following code snippet demonstrates the creation of a LinkedHashMap:

LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();
{
    linkedHashMap.put("apple", 10);
    linkedHashMap.put("orange", 20);
    linkedHashMap.put("banana", 15);
}

Here, we create a LinkedHashMap named linkedHashMap and populate it with some key-value pairs.

3. Iterating Through the Entry Set Approach

We can find a specific key’s position (index) in a LinkedHashMap by iterating through its Entry set. The following test method illustrates this approach:

@Test
void givenLinkedHashMap_whenIteratingThroughEntrySet_thenRetrievePositionByKey() {
    int position = 0;
    for (Map.Entry<String, Integer> entry : linkedHashMap.entrySet()) {
        if (entry.getKey().equals("orange")) {
            assertEquals(1, position);
            return;
        }
        position++;
    }
    fail("Key not found");
}

In this test method, we start by initializing a LinkedHashMap named linkedHashMap with specific key/value pairs. We then iterate through the entry set of this LinkedHashMap using a loop. During each iteration, we compare the key of the current entry with the target key orange using the entry. getKey().equals().

When a match is found, we assert that the current position (position) corresponds to the expected index 1 for the key (orange) within the insertion order of the LinkedHashMap and exit the method successfully.

After iterating through the entry set, the test will fail if the key isn’t found or the position is incorrect.

4. Using Java Streams

Another approach to solving this issue is using Java Streams. Here’s the implementation for this approach:

@Test
void givenLinkedHashMap_whenUsingJavaStreams_thenRetrievePositionByValue() {
    Optional<String> key = linkedHashMap.keySet().stream()
      .filter(integer -> Objects.equals(integer, "orange"))
      .findFirst();

    assertTrue(key.isPresent());
    key.ifPresent(s -> assertEquals(1, new LinkedList<>(linkedHashMap.keySet()).indexOf(s)));
}

In this test method, we utilize the linkedHashMap.keySet() method to return a set of the keys contained in the LinkedHashMap. Then, we create a stream of the keys by calling the stream() method on this set.

Afterward, we employ the filter() method to narrow down the stream elements based on a given predicate. In this case, it tries to find the key whose value is orange. After filtering, we call the findFirst() method to obtain the first element that matches the filter predicate.

The Optional<String> key represents the result of findFirst(), which may or may not contain a value based on whether a matching key was found. Therefore, we use the assertTrue(key.isPresent()) method.

5. Conclusion

In this article, we explored different approaches to getting the position of a key value within a LinkedHashMap in Java.

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

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1 Comment
Oldest
Newest