How to get random key-value pair from Hashtable?

package org.kodejava.example.util;

import java.util.Hashtable;
import java.util.Random;

public class HashtableGetRandom {
    public static void main(String[] args) {
        //
        // Create a hashtable and put some key-value pair.
        //
        Hashtable colors = new Hashtable();
        colors.put("black", "#000");
        colors.put("red", "#f00");
        colors.put("green", "#0f0");
        colors.put("blue", "#00f");
        colors.put("white", "#fff");

        //
        // Get a random entry from the hashtable.
        //
        Object[] keys = colors.keySet().toArray();
        Object key = keys[new Random().nextInt(keys.length)];
        System.out.println(key + " = " + colors.get(key));
    }
}

Wayan Saryada

A programmer, a slow runner, a recreational open water diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

Leave a Reply