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<String, String> 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.
        String[] keys = colors.keySet().toArray(new String[colors.size()]);
        String key = keys[new Random().nextInt(keys.length)];
        System.out.println(key + " = " + colors.get(key));
    }
}

How do I create a java.util.Hashtable and iterates its contents?

The code snippet shows you how to create and instance of Hashtable that stores Integer values using a String keys. After that we iterate the elements of the Hashtable using the Enumeration interface.

package org.kodejava.util;

import java.util.Enumeration;
import java.util.Hashtable;

public class HashtableDemo {
    public static void main(String[] args) {
        // Creates an instance of Hashtable
        Hashtable<String, Integer> numbers = new Hashtable<>();
        numbers.put("one", 1);
        numbers.put("two", 2);
        numbers.put("three", 3);

        // Returns an enumeration of the keys in this Hashtable
        Enumeration<String> keys = numbers.keys();
        while (keys.hasMoreElements()) {
            // Returns the next element of this enumeration if this
            // enumeration object has at least one more element to
            // provide
            String key = keys.nextElement();
            System.out.printf("Key: %s, Value: %d%n", key, numbers.get(key));
        }
    }
}