Tuesday, April 30, 2013

Iterate a HashMap


HashMap is an object that stores both “key/value” as a pairs.
It is one of the most useful data structures in the Java programming language.

Step by Step Iterating a HashMap :- 

Method 1 :-
Map<Integer, Integer> map = new HashMap<Integer, Integer>();

//iterating over keys only
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}

//iterating over values only
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}

Method 2 :-
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

No comments:

Post a Comment

ShareThis