Solved Picking a random player out of a HashMap

Discussion in 'Plugin Development' started by AlexHH251997, Jul 20, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    AlexHH251997

    Hi there,

    I wanted to know if you could help me out. I'm trying to pick two random players out of one HashMap and place them into another. I need to pick out two players. One player will be added to the weaponPlayer HashMap and the other player will be added to the murdererPlayer HashMap. The rest of the players will be placed into the bystanderPlayers HashMap. The problem is I don't know how to do it. If you could explain to me how to do it that would be great and I would appreciate it.

    Basically in a nutshell I'm looking to take two random players out of the lobbyPlayers HashMap. I want one to be placed in the weaponPlayer HashMap, one to be placed in the murdererPlayer HashMap and everyone that is left to be placed in the bystanderPlayers HashMap.

    Code:java
    1. //HASMAPS
    2. public static HashMap<Player, Player> lobbyPlayers = new HashMap<Player, Player>();
    3. public static HashMap<Player, Player> bystanderPlayers = new HashMap<Player, Player>();
    4. public static HashMap<Player, Player> weaponPlayer = new HashMap<Player, Player>();
    5. public static HashMap<Player, Player> murdererPlayer = new HashMap<Player, Player>();
     
  2. Offline

    fireblast709

    AlexHH251997 java.util.Random for a random index.
    Code:java
    1. Set<Entry<Player, Player>> set = map.entrySet();
    2. Entry<Player, Player>[] entries = set.toArray(new Entry<Player, Player>[set.size()]);
    to get an array of entries. Also, it is not adviced to use Player objects in a Map due to the ease of creating memory leaks
     
    AlexHH251997 likes this.
  3. Offline

    jeussa

    Getting a random player from a hashmap is easy. Let's start with a hashmap:

    Code:java
    1. public static HashMap<Player, Player> map = new HashMap<Player, Player>();


    Now let's get a random player either from the keys or the values (key = first variable, value = second variable, a value is obtained by a key)

    Code:java
    1. //Getting a random player which is a key inside the hashmap
    2. Player player = (Player)map.keySet().toArray()[new Random().nextInt(map.keySet().toArray().length)];
    3.  
    4. //Getting a random player which is a value inside the hashmap
    5. Player player = (Player)map.values().toArray()[new Random().nextInt(map.keySet().toArray().length)];
     
Thread Status:
Not open for further replies.

Share This Page