In this class i am going to show you how to iterate a map . Map is interface
which is part of the java collection framework.
1-Map is maps keys to values
2-Map cannot content duplicate keys
3-each key can map to at most one value.
4-Map is interface
5-Package is java.util
6-Map is collection of Object
7-you could access Maps following three way -
1-using set of keys
2-using set of value
3-using set of keys and values
package map;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @author
Prateek Shaw
* @version 0.1
*/
public class MapIteration {
public static void main(String[] args) {
Map
mapFirst = new HashMap();
for (int i = 1; i <= 5; i++) {
mapFirst.put("key" + i, i);
}
mapIterationThroughKeys(mapFirst);
mapIterationThroughEntitySet(mapFirst);
mapIterationThroughValues(mapFirst);
}
/**
* 1-Access key and value of map using keySet keySet is method which return
* the {@link Set} of key using this key we get the value.
*/
public static void mapIterationThroughKeys(Map
mapSecond) {
Set
setMap = mapSecond.keySet();
for (String key : setMap) {
System.out.println("Key------->" + key + " Value------>"
+ mapSecond.get(key));
}
}
/**
* 2-Access key and value of map using entitySet entityset method return the
* set{@link Set} type mappings contained in this map. this return the set
* which content the pair of key and value
*/
public static void mapIterationThroughEntitySet(Map
mapThird) {
Set
> setMap = mapThird.entrySet();
for (Map.Entry
key : setMap) {
System.out.println("Key------->" + key.getKey() + " Value------>"
+ key.getValue());
}
}
/**
* 1-Access value of map using values
*/
public static void mapIterationThroughValues(Map
mapFour) {
Collection
setMap = mapFour.values();
for (Integer value : setMap) {
System.out.println(" Value------>" + value);
}
}
}