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

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

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

13条回答
  •  鱼传尺愫
    2020-11-30 04:19

    Since the requirements only asks for a random value from the HashMap, here's the approach:

    1. The HashMap has a values method which returns a Collection of the values in the map.
    2. The Collection is used to create a List.
    3. The size method is used to find the size of the List, which is used by the Random.nextInt method to get a random index of the List.
    4. Finally, the value is retrieved from the List get method with the random index.

    Implementation:

    HashMap map = new HashMap();
    map.put("Hello", 10);
    map.put("Answer", 42);
    
    List valuesList = new ArrayList(map.values());
    int randomIndex = new Random().nextInt(valuesList.size());
    Integer randomValue = valuesList.get(randomIndex);
    

    The nice part about this approach is that all the methods are generic -- there is no need for typecasting.

提交回复
热议问题