Steerpike
Steerpike

Reputation: 1843

Decrementing values from a randomized HashMap

The context here is context is in allocating meals to airline passengers.

Given a HashMap called allMealsList which is extracted from an API response and looks like this:

enter image description here

...I want to choose a meal at random, and return it so an adult passenger has a random meal. Don't worry about the conditional if("adult"), I am handling that elsewhere.

Where I am struggling is in decrementing the correct value from the HashMap.

My method is as follows:

  public String chooseAvailableMeals(HashMap<String, Integer> allMealsList, String paxType) {

    for (Iterator<Map.Entry<String, Integer>> it = allMealsList.entrySet().iterator(); it.hasNext(); ) {

        Random generator = new Random();

        Map.Entry<String, Integer> entry = it.next();

        if (Objects.equals(paxType, "adult")) {

            Object[] meals = allMealsList.keySet().toArray();
            Object randomMeal = meals[generator.nextInt(meals.length)];

            entry.setValue(entry.getValue() - 1);
            return (String) randomMeal;
        }
    }

Where I do:

entry.setValue(entry.getValue() - 1);

It is, of course, decrementing not the value from the randomised key but of the first key - in this case "BBML".

Bear in mind I'm a relative java novice so I'm sure there is a more elegant or efficient way of doing this ;). Thank you in advance.

Upvotes: 2

Views: 337

Answers (1)

Eran
Eran

Reputation: 393811

You don't need to iterate over the entries of the HashMap, just retrieve the relevant value by its key:

public String chooseAvailableMeals(HashMap<String, Integer> allMealsList, String paxType) {

    Random generator = new Random();

    if (Objects.equals(paxType, "adult")) {

        Object[] meals = allMealsList.keySet().toArray();
        Object randomMeal = meals[generator.nextInt(meals.length)];

        Integer value = allMealsList.get(randomMeal);
        if (value != null && value > 0) {
            allMealsList.put(randomMeal, value - 1);
        }
        return (String) randomMeal;
    }

    // you should throw some exception or return some default value here
}

P.S. it would be better to create one Random instance outside of this method, and re-use it each time you need to generate a random number.

Upvotes: 1

Related Questions