Is there some way of initializing a Java HashMap like this?:
Map test =
new HashMap{\"test\":\"test\",\"test\
Unfortunately, using varargs if the type of the keys and values are not the same is not very reasonable as you'd have to use Object...
and lose type safety completely. If you always want to create e.g. a Map
, of course a toMap(String... args)
would be possible though, but not very pretty as it would be easy to mix up keys and values, and an odd number of arguments would be invalid.
You could create a sub-class of HashMap that has a chainable method like
public class ChainableMap extends HashMap {
public ChainableMap set(K k, V v) {
put(k, v);
return this;
}
}
and use it like new ChainableMap
Another approach is to use the common builder pattern:
public class MapBuilder {
private Map mMap = new HashMap<>();
public MapBuilder put(K k, V v) {
mMap.put(k, v);
return this;
}
public Map build() {
return mMap;
}
}
and use it like new MapBuilder
However, the solution I've used now and then utilizes varargs and the Pair
class:
public class Maps {
public static Map of(Pair... pairs) {
Map = new HashMap<>();
for (Pair pair : pairs) {
map.put(pair.first, pair.second);
}
return map;
}
}
Map
The verbosity of Pair.create()
bothers me a bit, but this works quite fine. If you don't mind static imports you could of course create a helper:
public Pair p(K k, V v) {
return Pair.create(k, v);
}
Map
(Instead of Pair
one could imagine using Map.Entry
, but since it's an interface it requires an implementing class and/or a helper factory method. It's also not immutable, and contains other logic not useful for this task.)