Selecting random key and value from Java HashMap

Here is the Java example that shows how to get the random key value set from a Hash Map in Java.

package info.balloons.SeleniumTest;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class App 
    public static void main( String[] args )
    	final Map<String, String> monthMap = new HashMap<String, String>();
		monthMap.put("01", "Jan");
		monthMap.put("02", "Feb");
		monthMap.put("03", "Mar");
		monthMap.put("04", "Apr");
		monthMap.put("05", "May");
		monthMap.put("06", "Jun");
		monthMap.put("07", "Jul");
		monthMap.put("08", "Aug");
		monthMap.put("09", "Sep");
		monthMap.put("10", "Oct");
		monthMap.put("11", "Nov");
		monthMap.put("12", "Dec");
    	Object randomName = monthMap.keySet().toArray()[new Random().nextInt(monthMap.keySet().toArray().length)];

Output will be random key value pair. For example


monthMap is a java HashMap. First the HashMap is converted into a Set Collection, from which it is converted into an Array and by Using Java Random function we can get the random key from the Array, which can be further used to get the value šŸ˜‰

Livewire Component Library

Site Footer