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.
Since Java 9, it is possible to use
Map.of(...)
, like so:This map is immutable. If you want the map to be mutable, you have to add:
If you can't use Java 9, you're stuck with writing a similar helper method yourself or using a third-party library (like Guava) to add that functionality for you.
Java has no map literal, so there's no nice way to do exactly what you're asking.
If you need that type of syntax, consider some Groovy, which is Java-compatible and lets you do:
Here's a simple class that will accomplish what you want
And then to use it
This yields
{a:1, b:2}