Search code examples
javaarraylistcomboboxhashmap

How to fill a combobox with hashmap keys?


I have a HashMap, and I want to fill a dropdownlist with the keys of the HashMap. The HashMap type is: HashMap<String, ArrayList<String>>

For example, the HashMap data is:

{A=[Ananas, Apple, Avocado], B=[Banana, Blueberries], C=[Cherries]}

So then I want a dropdown list with only once A, B and C.

I tried two ways, but in both cases I get multiple keys in my dropdown list. For example A, B, C, B, C. Can someone explain me why?

The two ways I tried:

    for (String key : FruitMap.keySet()) {
        Dropdown.addItem(key);
    }

and

    for (Map.Entry<String, ArrayList<String>> entry : FruitMap.entrySet()){
        String key = entry.getKey();
        Dropdown.addItem(key);

    }

Solution

  • The two ways you mentioned are correct, however, I would add:

    Dropdown.removeAllItems();
    

    before the loop.