Friday, May 31, 2013

Java - Duplicate key in java collection (Map, HashMap)

Required:
http://commons.apache.org/proper/commons-collections/

Source Code
import java.util.Set;
import java.util.Map;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.collections.map.MultiValueMap;
public class MultiMapExample {

   public static void main(String[] args) {
      MultiValueMap mp=new MultiValueMap();
      mp.put("a", 10);
      mp.put("a", 11);
      mp.put("a", 12);
      mp.put("b", 13);
      mp.put("c", 14);
      mp.put("e", 15);
      List list = null;

      Set set = mp.entrySet();
      Iterator i = set.iterator();
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         list=(List)mp.get(me.getKey());
       
         for(int j=0;j<list.size();j++)
         {
          System.out.println(me.getKey()+": value :"+list.get(j));
         }
      }
   }
}

Results:
a: value :10
a: value :11
a: value :12
c: value :14
b: value :13
e: value :15

0 comments:

Post a Comment