Powered by Blogger.

How to Iterate or Traverse a Map in Java

>> Sunday, June 22, 2014

Iterating a Map is not like a List Iteration. Map is having key-value pair to store the elements. Based on key,we can retrieve mapped value.To Iterate or loop a map we have 3 ways using with the help of Map.Entry, keySet() and entrySet()methods.
How to Iterate or Traverse a Map_Javabynataraj
Explanation about Map.Entry,keySet() and entrySet()
In Simple way we can say that, If you just need keys, use keySet(). If you just need values, use values(). If you're going to use keys and values in your subsequent code, then you're best to using entrySet().

java.util.Map.Entry<K,V>:A map entry (key-value pair). The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.

java.util.HashMap.keySet() method is used to get a set view of the keys contained in the map.

java.util.HashMap.entrySet() Returns a set view of the mappings contained in this map(both key and value).Each element in the returned set is a Map.Entry. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

While Iterating a map using keySet and Iterator using 'while' loop, we should follow the procedure to iterate as
  1. Convert map keys to Set 
  2. Pass the keys to Iterator reference itr2. 
  3. using itr2.next() get the key 
  4. get the value using map.get(key)
In the below program we can see how to work with while and for-each loop using keySet and entrySet. Program to Iterate Map<key,value>
package com.javabynataraj;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class IterateMap {
 public static void main(String[] args) {
  Map<Integer,String> map = new HashMap<Integer,String>();
  map.put(100, "Hundred");
  map.put(500, "Five Hundred");
  map.put(200, "Two Hundred");
  map.put(400, "Four Hundred");
  map.put(300, "Three Hundred");
  
  System.out.println("--Using keySet and Iterator--");
  Set<Integer> keys = map.keySet();
  Iterator<Integer> itr2 = keys.iterator();
   while(itr2.hasNext()){
     Integer key = itr2.next();
            String value = (String)map.get(key);
     System.out.println(key+"->"+value);
   }
  
  System.out.println("\n--Using entrySet and Iterator--");
  Iterator<Map.Entry<Integer,String>> itr = map.entrySet().iterator();
  while(itr.hasNext()){
       Map.Entry<Integer, String> entry = itr.next();
       System.out.println(entry);
       //System.out.println(entry.getKey()+"--"+entry.getValue());
  }
  
  System.out.println("\n--Using keySet in for-each loop--");
      for(Integer key: map.keySet()){
       System.out.println(key  +" :: "+ map.get(key));
      }
   
  System.out.println("\n--Using entrySet in for-each loop--");
    for(Map.Entry<Integer, String> entry : map.entrySet()){
      System.out.println(entry);
      //System.out.println(entry.getKey()+":"+entry.getValue());
  }
 }
}

Here i have compiled in MyEclipse.You can compile this code using command prompt like using this command javac -d . IterateMap.java This will generate you a packaged class inside the com.javabynataraj folder.
Output:
How to Iterate or Traverse a Map-Output_JavabynataraJ
Using entrySet to iterate or loop HashMap or Map is best practice than using keySet. Because every time you call get() you're making the JVM spend time doing a hashcode lookup, or navigating a tree and evaluating a comparator. Map.Entry gives you both key and value, together, in the most efficient manner possible.

Reference Books:

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.