Brejuro
Brejuro

Reputation: 3541

Iterate over a java map and change values

I have a map of <CheckBox, ImageButton>.

I want to be able to iterate over this map and change the image of each ImageButton. Is there any way I can do this? getValue() doesn't seem to let me use the methods associated with each ImageButton.

Upvotes: 1

Views: 1041

Answers (4)

scoot
scoot

Reputation: 11

// support you define your hash map like this
HashMap<CheckBox,ImageButton> hs = new HashMap<CheckBox,ImageButton>();
// then
for(Map.Entry<CheckBox, ImageButton> e : hs.entrySet())
{
    ImageButton imgBtn = e.getValue();
    // do whatever you like to imgBtn
}

Upvotes: 1

aProperFox
aProperFox

Reputation: 2164

Taken from this answer

You have to cast the result of getValue to an ImageButton to use its functions.

Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pair = (Map.Entry)it.next();
    ((ImageButton)pair.getValue()).setImageBitmap(bitmap);
}

Upvotes: 0

Sebastian
Sebastian

Reputation: 1074

You can iterate over the keys of a Map using keySet, and get the value associated with each individual key:

for (CheckBox cb : checkBoxes.keySet()) {
    ImageButton btn = checkBoxes.get(cb);
}

Upvotes: 0

Luka Jacobowitz
Luka Jacobowitz

Reputation: 23532

A HashMap? Use HashMap.values() to get a Collection of the saved Values. http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#values()

Upvotes: 0

Related Questions