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.
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);
}
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", ...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With