Choose random key from Hashmap

Discussion in 'Plugin Development' started by bluegru, Dec 20, 2013.

Thread Status:
Not open for further replies.
  1. Is there a way to chose a random key from a hashmap?

    I have a hashmap with player as key and want to get a random player from the list,
    I have a random number from 1 to the number of players in the hashmap

    how do I get a random key from the hashmap?
     
  2. bluegru
    Don't store player objects, store their names instead.

    And an answer to your question, something like this should work.
    Code:
    String randomName = someHashMap.keySet().get(new Random().nextInt(someHashMap.keySet().size()));
     
  3. There is no
    Code:java
    1. HashMap.keySet().get();
     
  4. Offline

    slayr288

  5. bluegru
    Whoops, sorry. I forgot that a Set doesn't have get() method. You could just turn the set into an array, and pick a random from that.
    Code:
    String randomName = someHashMap.keySet().toArray()[new Random().nextInt(someHashMap.keySet().toArray().length)];
    edit: now that I think of it, the keySet could be anything, not just string, so make that an Object.
     
Thread Status:
Not open for further replies.

Share This Page