Sunday, May 3, 2009

Java : Adding multiple values to a key in a HashMap / Hashtable

Hi guys,

In today's example I will show you how to add multiple values to a key in a HashMap or Hashtable.

The key is to add the values in an ArrayList everytime.

Check out the next example for more :

/*

  *   @(#)HashMapMultipleValues.java       1.1   03/05/09

  *

  *   Copyright   2009   Lazy   Coder.   All   rights   reserved.

  *   To   be   used   only   for   educational   purposes.

  *   Not   to   be   reproduced   and   published

  *   without   seeking   prior   consent.

  */


package   com.lazy.coder.examples;



import   java.util.ArrayList;

import   java.util.HashMap;



/**

  *   @author   lazycoder

  *

  */


public   class   HashMapMultipleValues   {

      

       public   static   void   addMultipleValues(HashMap   map,  

                     Object   key,   Object   value){

              Object   prevValue   =   map.get(key);

              ArrayList   valueList;

              if(   prevValue   ==   null   ){

                       valueList   =   new   ArrayList();

                       map.put(key,   valueList);

              }else{

                     valueList   =   (ArrayList)prevValue;

              }

                valueList.add(value);

       }



       /**

         *   @param   args

         */


       public   static   void   main(String[]   args)   {

              HashMap   map   =   new   HashMap();

              String   key   =   "LazyCoder";

              addMultipleValues(map,   key,   "LazyCoder");

              addMultipleValues(map,   key,   "is");

              addMultipleValues(map,   key,   "Lazy");

             

              ArrayList   valuesList   =   (ArrayList)map.get(key);

              for(Object   value   :   valuesList){

                     System.out.println(value);

              }

       }



}


If done normally like this :
  map.put(key,   "LazyCoder");

  map.put(key,   "is");

  map.put(key,   "Lazy");

the old value gets overriden with the latest value put against the key in the HashMap
in this case "Lazy" will be saved against the key in map.

LazyCoder
Signing off for now...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl