4

I have a question about HashMap creation. Is there a simple and fast way of HashMap creation? Maybe, concatenation of two arrays {1, 2, ...} and {"picture/one.png", "picture/two.png", ...}. I am interested in a neat solution. Best practice, so to say.

Every guidance or hint would be very helpful. Thanks.

EDIT: And yes, I know how to initiate a HashMap. And I looked in javadoc (not even once). Sorry for bad explanation of my question, maybe it is not very clear. Once more, I am interested in best practice solution. If the best practice solution is a for-loop, so that's it. If there are other options, please, show.

zds
  • 914
  • 1
  • 10
  • 22
  • No, you can't. Use a proper constructor of the class. – Luiggi Mendoza Nov 18 '14 at 16:57
  • But it wouldn't be that hard to create a general/static method that takes such a string and returns the hashmap created with the data items. – ControlAltDel Nov 18 '14 at 16:58
  • 1
    You can refer to this post http://stackoverflow.com/questions/507602/how-can-i-initialize-a-static-map or this one http://stackoverflow.com/questions/6802483/how-to-directly-initialize-a-hashmap-in-a-literal-way – hatem87 Nov 18 '14 at 17:00
  • http://stackoverflow.com/questions/36951414/initialize-a-map-hashmap-in-java/36951468#36951468 – Ramkumar Pillai Apr 30 '16 at 06:22

3 Answers3

5

Yes it is possible:

public static <K,V> Map<K,V> mapFromArrays(K[] keys,V[]values){
    HashMap<K, V> result=new HashMap<K, V>();
    for(int i=0;i<keys.length;i++){
        result.put(keys[i], values[i]);
    }
    return result;

}

Assuming that keys and values have the same length.

You may also use this function in a static initializer like this:

private static Integer[] keys=new Integer[]{1,2,3};
private static String[] values=new String[]{"first","second","third"};

private static Map<Integer,String> myMap;
{
    myMap=mapFromArrays(keys, values);
}
gorootde
  • 4,003
  • 4
  • 41
  • 83
  • 3
    I believe the question is more related to a declarative representation, rather than an actual function... – Fritz Nov 18 '14 at 17:01
  • The question is related to neat and fast solution, best practice so to say. – zds Nov 18 '14 at 17:07
  • k_wave, +1 I used your method-for-loop approach and initiated it in the constructor not in a block, because I need HashMap to be final. – zds Nov 19 '14 at 06:07
  • A slight improvement to this solution could be to change it to an "allAll" function (returning the map itself) instead of a "new object" function. Becoming ` Map addAllFromArrays(Map result, K[] keys,V[] values)` and used `myMap = addAllFromArrays(new HashMap(), keys, values)`. It allows to choose the type of Map, plus it expands its usefulness (to an addAll need/will). – syme Apr 03 '16 at 15:11
4

The short answer is NO. However, you can come close with varargs in a static utility function.

With no error checking, and no generics:

public static Map kvPairsToMap(Object...args) {
   // TODO check that args has an even length
   Map map = new HashMap();
   for (int i=0; i<args.length; i+=2) {
      map.put(args[i], args[i+1]);
   }

   return map;
}

Usage would be

Map dic = kvPairsToMap(1,"picture/one.png", 2,"picture/two.png", ...);
user949300
  • 15,364
  • 7
  • 35
  • 66
  • @zds Thanks. You can do similar varargs tricks with other key-value pairs, such as HTTP headers, queries, etc... – user949300 Nov 19 '14 at 04:23
1

Here is a way to initialize a map using variable declarations when the keys and values are Strings.

First declare a two dimensional array of Strings. Use the curly bracket notation to initialize the array, such as

final static String [][] animalEatsArray = {{"mouse", "cheese"}, {"dog", "bone"}};

Then declare and initialize the map:

final static Map animalEatsMap = buildMapFromStringArray(animalEatsArray );

You need a method like this somewhere:

public static Map<String, String> buildMapFromStringArray( String [] [] stringArray) {

    if (stringArray == null ) {
        throw new IllegalArgumentException("buildMapFromStringArray: stringArray is null");
    }

    Map<String, String> map = new HashMap<String, String>( 1 + (2 * stringArray.length) ); 

    for ( String[] keyValue : stringArray) {
        map.put(keyValue[0], keyValue[1]);
    }

    return map;
}
user2367418
  • 196
  • 1
  • 5