Monday, May 30, 2011

How to store multiple entries (basically key-value pairs) into some collection with a same key


public class HashMap2
{

        static HashMap map = new HashMap();

        public static void putVal(Object key, Object value)
        {

       if ( ! map.containsKey( key ) )
               {

                      List list = new ArrayList( );
                      list.add( value);
                      map.put( key, list);
              }
              else
              {

                      List list = (List) map.get(key);
                      list.add( value );
              }
        }

        public static void main( String[] args )
        {

                 putVal( new Integer( 2 ), "two" );
                putVal( new Integer( 4 ), "four" );
                putVal( new Integer( 4 ), "FOUR2" );

                System.out.println( "map = " + map );
                System.out.println();
        }
  }