1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
/* Iterate through the values of Java HashMap example This Java Example shows how to iterate through the values contained in the HashMap object. */ import java.util.Collection; import java.util.HashMap; import java.util.Iterator; public class IterateValuesOfHashMapExample { public static void main(String[] args) { //create HashMap object HashMap hMap = new HashMap(); //add key value pairs to HashMap hMap.put("1","One"); hMap.put("2","Two"); hMap.put("3","Three"); /* get Collection of values contained in HashMap using Collection values() method of HashMap class */ Collection c = hMap.values(); //obtain an Iterator for Collection Iterator itr = c.iterator(); //iterate through HashMap values iterator while(itr.hasNext()) System.out.println(itr.next()); } } /* Output would be Three Two One */ |
I would recommend to use something like:
[code]
for (Object key: hMap.keySet()) {
System.out.println(hMap.get(key));
}
[/code]
Or even better with a hMap using generics:
[code]
for (Map.Entry<int, string=””> entry: hMap.entrySet()) {
System.out.println(entry.getValue());
}
[/code]
Thanks for the better example.
It is easy to read and very compact.
This was very helpful,thanks a lot
god bless you
Very helpful! Thanks!
Because it is compact
[code]
for (Object key: hMap.keySet()) {
System.out.println(hMap.get(key));
}
[/code]
Why not just use:
[code]
for ( Object x : hMap.values() ) {
System.out.println(x);
}
[/code]
is it bad?
[code]
Set set=hMap.entrySet();
Iterator iii=set.iterator();
while (itr.hasNext()) {
Object object = (Object) itr.next();
System.out.println(“**********”);
System.out.println(“Set values is “+object);
}
[/code]
good examples really
nice program
why is it not working if i try to work with the values which itsself are objects of another class ?
[code]
Collection c = allLendings.values();
Iterator itr = c.iterator();
while(itr.hasNext())
{
String[] date = itr.next().getLend().split(“.”);
if(date[1] == month)
{
. ….
}
}
[/code]
Hi,
Iterator’s next method returns object. So you need to cast it to appropriate class before invoking its method.
Hope this helps.
Thanks.
[code]
Iterator hashIterator = hashMapName.keySet().iterator();
while(hashIterator.hasNext()) {
Type variable = hashIterator.next();
Type2 variable2 = hashMapName.get(variable);
…
}
[/code]
how can i sort by a attrubite from objact that is a value in a map
this tip save my life