HashMap initialization in java
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;
}
![zds](https://i.stack.imgur.com/jWHJ9.png?s=256&g=1)
zds
Eager to know... Having or showing keen interest, intense desire, or impatient expectancy for knowledge
Updated on February 02, 2021Comments
-
zds over 3 years
I have a question about
HashMap
creation. Is there a simple and fast way ofHashMap
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 over 9 yearsI believe the question is more related to a declarative representation, rather than an actual function...
-
zds over 9 yearsThe question is related to neat and fast solution, best practice so to say.
-
user949300 over 9 years@zds Thanks. You can do similar varargs tricks with other key-value pairs, such as HTTP headers, queries, etc...
-
zds over 9 yearsk_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 over 8 yearsA 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 usedmyMap = 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).