/*
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
*/
Bookmark/Search this post with:
More modern alternative
I would recommend to use something like:
for (Object key: hMap.keySet()) {
System.out.println(hMap.get(key));
}
Or even better with a hMap using generics:
for (Map.Entry entry: hMap.entrySet()) {
System.out.println(entry.getValue());
}
Very helpful! Thanks!
Very helpful! Thanks!
hm
why is it not working if i try to work with the values which itsself are objects of another class ?
Collection c = allLendings.values();
Iterator itr = c.iterator();
while(itr.hasNext())
{
String[] date = itr.next().getLend().split(".");
if(date[1] == month)
{
. ....
}
}
Iterator returns object
Hi,
Iterator's next method returns object. So you need to cast it to appropriate class before invoking its method.
Hope this helps.
Thanks.
Post new comment