1. Overview
In Java, a HashMap is a common data structure for storing key-value pairs. While it’s efficient for many operations, we may need to access data in a HashMap randomly. Whether for testing, random selection, or other use cases, retrieving random keys, values, or entries can be tricky because a HashMap is structured in a way that makes it difficult to do so.
In this tutorial, we’ll explore different methods for retrieving a random key, value, or entry from a HashMap. We’ll also walk through some code examples that demonstrate each approach.
For simplicity, we’ll use unit tests to demonstrate solutions in this tutorial. So, let’s first create a test class and initialize a HashMap object as input:
public class RandomlyPickDataFromHashMapUnitTest {
private static final HashMap<String, String> dataMap = new HashMap<>();
@BeforeAll
public static void setupMap() {
dataMap.put("Key-A", "Value: A");
dataMap.put("Key-B", "Value: B");
dataMap.put("Key-C", "Value: C");
dataMap.put("Key-D", "Value: D");
dataMap.put("Key-E", "Value: E");
dataMap.put("Key-F", "Value: F");
dataMap.put("Key-G", "Value: G");
dataMap.put("Key-H", "Value: H");
dataMap.put("Key-I", "Value: I");
}
// ...
}
In this test class, we use a @BeforeAll method to initialize the dataMap object for all test methods.
3. Getting a Random Key
Getting a random key from a HashMap is a common scenario when we need to perform actions based on a randomly selected entry. There are multiple ways to achieve this in Java.
Next, we’ll walk through three common approaches: using arrays, iterators, and streams. For simplicity, we’ll skip null and empty checks in this tutorial.
3.1. Using an Array
One way to pick a random key is by converting the set of keys into an array. We can then randomly select an index and return the corresponding key.
<K, V> K randomKeyUsingArray(HashMap<K, V> map) {
K[] keys = (K[]) map.keySet().toArray();
Random random = new Random();
return keys[random.nextInt(keys.length)];
}
As we can see, this approach works by converting the set of keys to an array using toArray(). We then generate a random index and return the corresponding key.
Next, let’s create a test method to call randomKeyUsingArray()Â three times and observe the output:
for (int i = 0; i < 3; i++) {
String key = randomKeyUsingArray(dataMap);
LOG.info("Random Key (Array): {}", key);
}
When we run this code, it produces this output:
15:39:50.044 [main] INFO ... Random Key (Array): Key-I
15:39:50.046 [main] INFO ... Random Key (Array): Key-B
15:39:50.046 [main] INFO ... Random Key (Array): Key-F
Converting the key-set to an array is straightforward. However, it iterates through all keys. This can be slow when working on a HashMap with a large number of entries.
3.2. Using an Iterator
Alternatively, we can first generate a random index and then create an Iterator  over the set of keys and iterate until we reach the target index:
<K, V> K randomKeyUsingIterator(HashMap<K, V> map) {
Random random = new Random();
int targetIndex = random.nextInt(map.size());
Iterator<K> iterator = map.keySet().iterator();
K currentKey = null;
for (int i = 0; i <= targetIndex; i++) {
currentKey = iterator.next();
}
return currentKey;
}
Next, let’s call this method three times and see what keys it returns:
for (int i = 0; i < 3; i++) {
String key = randomKeyUsingIterator(dataMap);
LOG.info("Random Key (Iterator): {}", key);
}
We get the following output if we run it:
16:14:24.915 [main] INFO ... Random Key (Iterator): Key-F
16:14:24.917 [main] INFO ... Random Key (Iterator): Key-G
16:14:24.917 [main] INFO ... Random Key (Iterator): Key-E
This approach doesn’t always iterate through all the keys in the map. Instead, it iterates the calculated random index +1 keys. Therefore, if we work with massive HashMap objects, this approach offers better performance than the array-based one.
3.3. Using the Stream API
Java 8 introduced Streams, which can be used to select a key concisely and elegantly randomly:
<K, V> K randomKeyUsingStream(HashMap<K, V> map) {
Random random = new Random();
return map.keySet()
.stream()
.skip(random.nextInt(map.size()))
.findFirst()
.orElseThrow();
}
This approach uses the stream() method to create a stream from the set of keys, skips a random number of elements, and returns the first element in the resulting stream.
Next, let’s see which three keys this approach will give us:
for (int i = 0; i < 3; i++) {
String key = randomKeyUsingStream(dataMap);
LOG.info("Random Key (Stream): {}", key);
}
Output:
16:26:48.285 [main] INFO ... Random Key (Stream): Key-F
16:26:48.287 [main] INFO ... Random Key (Stream): Key-H
16:26:48.287 [main] INFO ... Random Key (Stream): Key-D
Similar to the iterator-based solution, this approach doesn’t always iterate through all keys either. Further, thanks to the Stream API, this functional solution is fluent, elegant, and easy to read. Therefore, it is a good choice if we work with Java 8 or a later version.
4. Getting a Random Value
Now that we’ve discussed how to retrieve random keys. HashMap is a structure of key-value pairs. That is, if we obtain a random key using any solution we’ve learned, we can get its corresponding value by calling hashMap.get(randomKey).
Alternatively, HashMap offers the values() method to return a Collection view of all values contained in the map. So, we can randomly pick one value from the values() result. To do that, we can still use the same techniques we’ve learned: using an array, an Iterator, or a Stream.
Next, let’s use the Stream approach as an example to show how it works:
<K, V> V randomValueUsingStream(HashMap<K, V> map) {
Random random = new Random();
return map.values()
.stream()
.skip(random.nextInt(map.size()))
.findFirst()
.orElseThrow();
}
As the example shows, the logic is the same as obtaining a random key using the Stream approach.
5. Getting a Random Entry
As we mentioned, if we want a random key-value pair from a HashMap, we can first pick a random key and then use HashMap.get() to retrieve the corresponding value. However, sometimes, we would like to obtain a random Map.Entry object from a HashMap. In this case, we can first get the entry set of the HashMap using HashMap.entrySet(), then pick a random element from the set.
Next, let’s use the Stream approach as an example to show how it works:
<K, V> HashMap.Entry<K, V> randomEntryUsingStream(HashMap<K, V> map) {
Random random = new Random();
return map.entrySet()
.stream()
.skip(random.nextInt(map.size()))
.findFirst()
.orElseThrow();
}
As we can see, it’s pretty similar to other stream-based approaches we have learned.
6. Conclusion
In this article, we explored different ways to randomly retrieve data from a HashMap in Java.
By understanding these techniques, we can handle a broader range of real-world scenarios more effectively.
As always, the complete source code for the examples is available over on GitHub.