Is there a way to get the value of a HashMap randomly in Java?

前端 未结 13 2157
心在旅途
心在旅途 2020-11-30 03:45

Is there a way to get the value of a HashMap randomly in Java?

13条回答
  •  囚心锁ツ
    2020-11-30 04:09

    This works:

    Random generator = new Random();
    Object[] values = myHashMap.values().toArray();
    Object randomValue = values[generator.nextInt(values.length)];
    

    If you want the random value to be a type other than an Object simply add a cast to the last line. So if myHashMap was declared as:

    Map myHashMap = new HashMap();
    

    The last line can be:

    String randomValue = (String) values[generator.nextInt(value.length)];
    

    The below doesn't work, Set.toArray() always returns an array of Objects, which can't be coerced into an array of Map.Entry.

    Random generator = new Random();
    Map.Entry[] entries = myHashMap.entrySet().toArray();
    randomValue = entries[generator.nextInt(entries.length)].getValue();
    

提交回复
热议问题