how to get a random entry from a hashmap in java code example
Example: get a random value in hasmap java
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;
public class CrunchifyGetRandomKeyValueFromHashMap {
public static void main(String[] args) {
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");
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());
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());
}
}
}