Search code examples
javadictionaryrandomhashmaptreemap

Selecting random key and value sets from a Map in Java


I want to get random keys and their respective values from a Map. The idea is that a random generator would pick a key and display that value. The tricky part is that both key and value will be strings, for example myMap.put("Geddy", "Lee").


Solution

  • HashMap<String, String> x;
    
    Random       random    = new Random();
    List<String> keys      = new ArrayList<String>(x.keySet());
    String       randomKey = keys.get( random.nextInt(keys.size()) );
    String       value     = x.get(randomKey);