I need to initialize a constant HashMap and would like to do it in one line statement. Avoiding sth like this:
hashMap.put("One", new Integer(1)); // adding value into HashMap
hashMap.put("Two", new Integer(2));
hashMap.put("Three", new Integer(3));
similar to this in objective C:
[NSDictionary dictionaryWithObjectsAndKeys:
@"w",[NSNumber numberWithInt:1],
@"K",[NSNumber numberWithInt:2],
@"e",[NSNumber numberWithInt:4],
@"z",[NSNumber numberWithInt:5],
@"l",[NSNumber numberWithInt:6],
nil]
I have not found any example that shows how to do this having looked at so many.
Another approach may be writing special function to extract all elements values from one string by regular-expression:
Ignoring the declaration of
x
(which is necessary to avoid an "unreachable statement" diagnostic), technically it's only one statement.Maps have also had factory methods added in Java 9. For up to 10 entries Maps have overloaded constructors that take pairs of keys and values. For example we could build a map of various cities and their populations (according to google in October 2016) as follow:
The var-args case for Map is a little bit harder, you need to have both keys and values, but in Java, methods can’t have two var-args parameters. So the general case is handled by taking a var-args method of
Map.Entry<K, V>
objects and adding a staticentry()
method that constructs them. For example:Collection Factory Methods in Java 9
You could add this utility function to a utility class:
Note: in
Java 9
you can use Map.ofYou can use Google Guava's ImmutableMap. This works as long as you don't care about modifying the Map later (you can't call .put() on the map after constructing it using this method):
See also: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableMap.html
A somewhat related question: ImmutableMap.of() workaround for HashMap in Maps?
You can do this: