There are multiple ways to iterate through a Java
Map. Assuming the following map declaration:
Map<String,Object> m = new HashMap<String,Object>();
Here are the mutliple ways to iterate it.
Iterate on Keys and Values
// With an Iterator (with Generics)
Iterator<Entry<String, Object>> iterator
= m.entrySet().iterator();
while ( iterator.hasNext() ) {
Entry<String, Object> item = iterator.next();
System.out.println(item.getKey()
+ " - " + item.getValue());
}
// Without an Iterator (without Generics)
Iterator iterator2 = m.entrySet().iterator();
while ( iterator2.hasNext() ) {
Entry item = (Entry) iterator.next();
System.out.println(item.getKey()
+ " - " + item.getValue());
}
// Using For Each (with Generics)
for ( Entry<String, Object> item : m.entrySet() ) {
System.out.println(item.getKey()
+ " - " + item.getValue());
}
// Using For Each (without Generics)
for ( Entry item : m.entrySet() ) {
System.out.println(item.getKey()
+ " - " + item.getValue());
}
// Inefficient (fetching value from key)
for ( String key : m.keySet() ) {
System.out.println(key + " - " + m.get(key));
}
Iterate on Keys Only
for ( String key : m.keySet() ) {
System.out.println(key);
}
Iterate on Values Only
for ( Object value : m.values() ) {
System.out.println(value);
}
No comments:
Post a Comment