Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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 – Black Friday 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

1. Overview

Maps are fundamental data structures we might use every day in our code. At the same time, its main benefit, constant time access, in some cases might create problems when we try to combine it with accessing random elements in a map. This is a relatively rare case; at the same time, when we need to achieve this, it’s unclear how to do it efficiently.

In this tutorial, we’ll review several methods for accessing random elements from a map and discuss their advantages and disadvantages. Based on the tradeoffs, we can pick the most suitable approach for us.

2. Using a Random Number

If we consider this task in the context of a simple ArrayList, we won’t encounter any issues with the solution. Thus, we can consider a few options in which picking a random number would be one of the crucial steps.

2.1. Converting to an ArrayList

The most straightforward solution is to get a random key by converting a key set into an ArrayList and accessing an element using a random index:

public <K, V> V getRandomValueUsingList(Map<K, V> map) {
    if (map == null || map.isEmpty()) {
        return null;
    }

    List<K> keys = new ArrayList<>(map.keySet());
    K randomKey = keys.get(ThreadLocalRandom.current().nextInt(keys.size()));
    return map.get(randomKey);
}

While this solution appears simple, it has a significant drawback: it requires additional space. Also, even though the access to a random element in the ArrayList is constant, we have a hidden time complexity. The time complexity cannot be less than the space complexity. We need n iterations to copy or convert a set of length n to an array. However, if we can reuse the same array multiple times and the original set doesn’t change significantly, this solution may show good overall performance.

To use this function, we need to pass an original map and then we can retrieve a random value from it:

private final RandomNumberMap randomNumberMap = new RandomNumberMap();

@Test
public void whenGettingRandomValue_thenValueExistsInMap() {
    Map<String, Integer> map = new HashMap<>();
    map.put("apple", 1);
    map.put("banana", 2);
    map.put("cherry", 3);
    map.put("date", 4);
    map.put("elderberry", 5);

    Integer randomValue = randomNumberMap.getRandomValueUsingList(map);

    assertNotNull(randomValue);
    assertTrue(map.containsValue(randomValue));
}

Since our goal is to randomize the result, we cannot make any assumptions about the values we’re getting. However, the code should return only the values that were present in the original map.

2.2. Using Iteration

For cases where we need to perform this operation rarely or the original set changes frequently, we can use iteration directly on the set. It won’t allow indexed access, but we can skip a specific number of elements:

public <K, V> V getRandomValueUsingOffset(Map<K, V> map) {
    if (map == null || map.isEmpty()) {
        return null;
    }

    int randomOffset = ThreadLocalRandom.current().nextInt(map.size());
    Iterator<Entry<K, V>> iterator = map.entrySet().iterator();
    for (int i = 0; i < randomOffset; i++) {
        iterator.next();
    }

    return iterator.next().getValue();
}

Although this solution appears inferior to the first one, it would actually yield better results for one-off operations. Thus, we should consider how often and where this piece of code would be used, as well as the boundaries on the number of elements. The example of the usage is pretty similar to the previous implementation.

3. Shuffling a Set

Another approach, which might be overkill, is to shuffle the entire array and pick the first element. This approach would still require converting the set into an ordered collection:

public <K, V> K getRandomKeyUsingShuffle(Map<K, V> map) {
    if (map == null || map.isEmpty()) {
        return null;
    }

    List<K> keys = new ArrayList<>(map.keySet());
    Collections.shuffle(keys);

    return keys.get(0);
}

The time complexity of this approach is worse than the previous options. However, this one has a very nice quality: we can deplete the shuffled collection until it’s empty. In this case, we can use this collection as a source of randomized values. However, this would prevent the same values from appearing in the same randomization session, so it might not be appropriate for all cases.

Additionally, although we don’t pass ThreadLocalRandom or Random to the shuffle() function, it would be created internally. Therefore, this approach requires all the features we’ve used in the previous ones and may be desirable only for specific cases and requirements.

4. Custom Wrapper

However, if we require an implementation that works efficiently even when the map is frequently updated and we need proper randomization, we can build a custom solution. We’ll start with a simple wrapper and expose only basic operations:

public class RandomKeyTrackingMap<K, V> {

    private final Map<K, V> delegate = new HashMap<>();
    private final List<K> keys = new ArrayList<>();

    public void put(K key, V value) {
        V previousValue = delegate.put(key, value);
        if (previousValue == null) {
            keys.add(key);
        }
    }

    public V remove(K key) {
        V removedValue = delegate.remove(key);
        if (removedValue != null) {
            int index = keys.indexOf(key);
            if (index >= 0) {
                keys.remove(index);
            }
        }
        return removedValue;
    }

    public V getRandomValue() {
        if (keys.isEmpty()) {
            return null;
        }

        int randomIndex = ThreadLocalRandom.current().nextInt(keys.size());
        K randomKey = keys.get(randomIndex);
        return delegate.get(randomKey);
    }

}

The main issue is the remove() operation, as we need to remove a value from both a map and a list. However, to make this operation performant, we should add another data structure to track the indexes to the keys:

private final Map<K, V> delegate = new HashMap<>();
private final List<K> keys = new ArrayList<>();
private final Map<K, Integer> keyToIndex = new HashMap<>();

public void put(K key, V value) {
    V previousValue = delegate.put(key, value);
    if (previousValue == null) {
        keys.add(key);
        keyToIndex.put(key, keys.size() - 1);
    }
}

We can improve the solution and use swap instead of remove, so we continuously remove the last element, making the operation constant:

public V remove(K key) {
    V removedValue = delegate.remove(key);
    if (removedValue != null) {
        Integer index = keyToIndex.remove(key);
        if (index != null) {
            removeKeyAtIndex(index);
        }
    }
    return removedValue;
}

private void removeKeyAtIndex(int index) {
    int lastIndex = keys.size() - 1;
    if (index == lastIndex) {
        keys.remove(lastIndex);
        return;
    }

    K lastKey = keys.get(lastIndex);
    keys.set(index, lastKey);
    keyToIndex.put(lastKey, index);
    keys.remove(lastIndex);
}

While it adds some code, it makes this approach work in amortized linear time. After the implementation, we can use the map in the following way:

@Test
public void whenGettingRandomValue_thenValueExistsInMap() {
    OptimizedRandomKeyTrackingMap<String, Integer> map = new OptimizedRandomKeyTrackingMap<>();
    map.put("apple", 1);
    map.put("banana", 2);
    map.put("cherry", 3);

    Integer randomValue = map.getRandomValue();

    assertNotNull(randomValue);
    assertTrue(Arrays.asList(1, 2, 3).contains(randomValue));
}

Also, this implementation allows us to remove the values via the wrapper (the previous ones could use a reference to the original map, but it might cause hard-to-debug issues):

@Test
public void whenRemovingValue_thenRandomValueDoesNotContainRemovedEntry() {
    OptimizedRandomKeyTrackingMap<String, Integer> map = new OptimizedRandomKeyTrackingMap<>();
    map.put("apple", 1);
    map.put("banana", 2);
    map.put("cherry", 3);

    map.remove("banana");

    Integer randomValue = map.getRandomValue();

    assertNotNull(randomValue);
    assertTrue(Arrays.asList(1, 3).contains(randomValue));
}

We can expand the wrapper with additional methods and functionalities based on the requirements and the context in which we plan to use this class.

5. Extending a HashMap

A map itself contains information about the internal values and nodes. However, the table is an array of buckets. While we can pick the buckets uniformly, we cannot do this with the elements, since some buckets might be empty or contain multiple elements. The entrySet has the same problem as a Map (it also uses a Map internally), so we cannot get a random value from an unordered collection:

// Rest of HashMap implementation

/**
 * The table, initialized on first use, and resized as
 * necessary. When allocated, length is always a power of two.
 * (We also tolerate length zero in some operations to allow
 * bootstrapping mechanics that are currently not needed.)
 */
transient Node<K,V>[] table;

/**
 * Holds cached entrySet(). Note that AbstractMap fields are used
 * for keySet() and values().
 */
transient Set<Map.Entry<K,V>> entrySet;

// Rest of HashMap implementation

At the same time, we can create a new map implementation. This would allow the class to be seamlessly integrated into the rest of the code. However, this approach requires more code, since we need to satisfy all the Map methods and ensure that we won’t break anything:

public class RandomizedMap<K, V> extends HashMap<K, V> {
    
    private final Map<Integer, K> numberToKey = new HashMap<>();
    private final Map<K, Integer> keyToNumber = new HashMap<>();
    @Override
    public V put(K key, V value) {
        V oldValue = super.put(key, value);
        
        if (oldValue == null) {
            int number = this.size() - 1;
            numberToKey.put(number, key);
            keyToNumber.put(key, number);
        }
        
        return oldValue;
    }
    
    @Override
    public V remove(Object key) {
        V removedValue = super.remove(key);
        
        if (removedValue != null) {
            removeFromTrackingMaps(key);
        }
        
        return removedValue;
    }
    
    public V getRandomValue() {
        if (this.isEmpty()) {
            return null;
        }
        
        int randomNumber = ThreadLocalRandom.current().nextInt(this.size());
        K randomKey = numberToKey.get(randomNumber);
        return this.get(randomKey);
    }
    // Other methods
}

The remove functionality should cover more cases compared to the previous example:

private void removeFromTrackingMaps(Object key) {
    @SuppressWarnings("unchecked")
    K keyToRemove = (K) key;
    
    Integer numberToRemove = keyToNumber.get(keyToRemove);
    if (numberToRemove == null) {
        return;
    }
    
    int mapSize = this.size();
    int lastIndex = mapSize;
    
    if (numberToRemove == lastIndex) {
        numberToKey.remove(numberToRemove);
        keyToNumber.remove(keyToRemove);
    } else {
        K lastKey = numberToKey.get(lastIndex);
        if (lastKey == null) {
            numberToKey.remove(numberToRemove);
            keyToNumber.remove(keyToRemove);
            return;
        }
        
        numberToKey.put(numberToRemove, lastKey);
        keyToNumber.put(lastKey, numberToRemove);
        
        numberToKey.remove(lastIndex);
        
        keyToNumber.remove(keyToRemove);
    }
}

This is a more complex solution that requires aligning it with the Map interface. Therefore, it’s the best option when the class should align with the Map interface in other parts of the code.

6. Conclusion

Object-oriented programming languages (and almost all languages in general) allow us to create customized solutions for the problems we face. For some reason, this quality is often overlooked. When standard libraries don’t provide solutions or features out of the box, developers encounter problems with them. It’s important to remember that if we don’t have a specific functionality, we can always build it from scratch.

As usual, all the code from this tutorial is available over on GitHub.

Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

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.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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.

Course – Black Friday 2025 – NPI (All)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)
guest
0 Comments
Oldest
Newest
Inline Feedbacks
View all comments