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.

4

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

I believe the question is more related to a declarative representation, rather than an actual function...
The question is related to neat and fast solution, best practice so to say.
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.
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).
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", ...);

1 Comment

@zds Thanks. You can do similar varargs tricks with other key-value pairs, such as HTTP headers, queries, etc...
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.