Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap initialization in java

Tags:

java

hashmap

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.

like image 644
zds Avatar asked Oct 17 '25 04:10

zds


2 Answers

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);
}
like image 197
gorootde Avatar answered Oct 18 '25 18:10

gorootde


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", ...);
like image 43
user949300 Avatar answered Oct 18 '25 19:10

user949300