Monday, March 3, 2014

Iterating Map in Java using KeySet Iterator && using EntrySet



HashMap
Set<String> keySet = loans.keySet();
Iterator<String> keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
   System.out.println("------------------------------------------------");
   System.out.println("Iterating Map using KeySet Iterator");
   String key = keySetIterator.next();
   System.out.println("key: " + key + " value: " + loans.get(key));
}

Output:
------------------------------------------------
Iterating Map using KeySet Iterator
key: home loan value: citibank
------------------------------------------------
Iterating Map using KeySet Iterator
key: personal loan value: Wells Fargo

Example for using EntrySet
Set<Map.Entry<String, String>> entrySet = loans.entrySet();
for (Entry entry : entrySet) {
   System.out.println("------------------------------------------------");
   System.out.println("looping HashMap in Java using EntrySet and java5 for loop");
   System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}

Output:
------------------------------------------------
looping HashMap in Java using EntrySet and java5 for loop
key: home loan value: citibank
------------------------------------------------
looping HashMap in Java using EntrySet and java5 for loop
key: personal loan value: Wells Fargo

No comments:

Post a Comment