get a random value in hasmap java

Solutions on MaxInterview for get a random value in hasmap java by the best coders in the world

showing results for - "get a random value in hasmap java"
Drew
25 Jan 2020
1package com.crunchify.tutorials;
2 
3import java.util.ArrayList;
4import java.util.Collections;
5import java.util.HashMap;
6import java.util.List;
7import java.util.Map;
8import java.util.Random;
9 
10/**
11 * @author Crunchify.com
12 * 
13 */
14 
15public class CrunchifyGetRandomKeyValueFromHashMap {
16	public static void main(String[] args) {
17		//
18		// Create a hashtable and put some key-value pair.
19		//
20		HashMap<String, String> companies = new HashMap<String, String>();
21		companies.put("eBay", "South San Jose");
22		companies.put("Paypal", "North San Jose");
23		companies.put("Google", "Mountain View");
24		companies.put("Yahoo", "Santa Clara");
25		companies.put("Twitter", "San Francisco");
26 
27		// Get a random entry from the HashMap.
28		Object[] crunchifyKeys = companies.keySet().toArray();
29		Object key = crunchifyKeys[new Random().nextInt(crunchifyKeys.length)];
30		System.out.println("************ Random Value ************ \n" + key + " :: " + companies.get(key));
31 
32		List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(companies.entrySet());
33 
34		// Bonus Crunchify Tips: How to Shuffle a List??
35		// Each time you get a different order...
36		System.out.println("\n************ Now Let's start shuffling list ************");
37		Collections.shuffle(list);
38		for (Map.Entry<String, String> entry : list) {
39			System.out.println(entry.getKey() + " :: " + entry.getValue());
40		}
41	}
42}
43