Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java HashMap Litteral Creator

DZone's Guide to

Java HashMap Litteral Creator

·
Free Resource
// Here is a nice helper to create on the fly litteral hashmap.
// this makes use of Java 1.5 generic methods / class parametrization. 
//
// Example of usage :
//    
// import static Utils.*
// 
// ... 
// 
// HashMap
 
   = map("toto", 2, "titi", 3)
//
//

class Utils {

    /** Create a quick litteral map */
    public static 
  
    HashMap
   
     map(K key1, V val1, Object ... others) {
        
        // Create result hashmap
        HashMap
    
      map = new HashMap
     
      ();
        
        // Add first key/val pair
        map.put(key1, val1);
        
        // Check number of args
        if (others.length % 2 != 0) throw new Error("There should be a even number of arguments");
        
        // Loop on pairs
        for (int i=0; i < others.length % 2; i++) {
            
            // Get key / val
            K key = (K) others[2*i];
            V val = (V) others[2*i + 1];
            
            // Add it to the map
            map.put(key, val);
          
            
        } // End of loop on pairs
        
        return map;    
    }
}
     
    
   
  
 
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}