HashMap initialization in java

40,828

Solution 1

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);
}

Solution 2

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", ...);

Solution 3

There is a good way to Create HashMap Using Anonymous Subclass in this condition see example below :

     Map<Integer, String> map = new HashMap<Integer, String>() {{
     put(1,"picture/one.png");
     put(2,"picture/two.png");
     put(3,"picture/three.png");
    }};

Source : Ways For Creating HashMap

Solution 4

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;
}
Share:
40,828
zds
Author by

zds

Eager to know... Having or showing keen interest, intense desire, or impatient expectancy for knowledge

Updated on February 02, 2021

Comments

  • zds
    zds over 3 years

    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.

  • Fritz
    Fritz over 9 years
    I believe the question is more related to a declarative representation, rather than an actual function...
  • zds
    zds over 9 years
    The question is related to neat and fast solution, best practice so to say.
  • user949300
    user949300 over 9 years
    @zds Thanks. You can do similar varargs tricks with other key-value pairs, such as HTTP headers, queries, etc...
  • zds
    zds over 9 years
    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.
  • syme
    syme over 8 years
    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 <K,V> Map<K,V> addAllFromArrays(Map<K,V> result, K[] keys,V[] values) and used myMap = addAllFromArrays(new HashMap<Integer, String>(), keys, values). It allows to choose the type of Map, plus it expands its usefulness (to an addAll need/will).