Java: How to Get Random Key-Value Element From HashMap

Last updated
App Shah
Crunchify » Java and J2EE Tutorials » Java: How to Get Random Key-Value Element From HashMap

How to Get Random Key-Value Element From HashMap

Is there a way to get the value of a HashMap randomly in Java? Of Course, below is a simple Java Code which represents the same.

Also, at the end of program there is a bonus code to Shuffle complete HashMap. Reshuffling a large collection is always going to be expensive. You are going to need at least one reference per entry. e.g. for 1 million entries you will need approx 4 MB.

Note; the shuffle operation is O(N)

package com.crunchify.tutorials;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author crunchify.com
 * 
 */

public class CrunchifyGetRandomKeyValueFromHashMap {
	public static void main(String[] args) {
		//
		// Create a hashtable and put some key-value pair.
		//
		HashMap<String, String> companies = new HashMap<String, String>();
		companies.put("eBay", "South San Jose");
		companies.put("Paypal", "North San Jose");
		companies.put("Google", "Mountain View");
		companies.put("Yahoo", "Santa Clara");
		companies.put("Twitter", "San Francisco");

		// Get a random entry from the HashMap.
		Object[] crunchifyKeys = companies.keySet().toArray();
		Object key = crunchifyKeys[new Random().nextInt(crunchifyKeys.length)];
		System.out.println("************ Random Value ************ \n" + key + " :: " + companies.get(key));

		List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(companies.entrySet());

		// Bonus Crunchify Tips: How to Shuffle a List??
		// Each time you get a different order...
		System.out.println("\n************ Now Let's start shuffling list ************");
		Collections.shuffle(list);
		for (Map.Entry<String, String> entry : list) {
			System.out.println(entry.getKey() + " :: " + entry.getValue());
		}
	}
}

Other must read:

Output:

************ Random Value ************ 
Twitter :: San Francisco

************ Now Let's start shuffling list ************
Paypal :: North San Jose
eBay :: South San Jose
Google :: Mountain View
Twitter :: San Francisco
Yahoo :: Santa Clara

2 thoughts on “Java: How to Get Random Key-Value Element From HashMap”

Leave a Comment