user387184 user387184 - 1 year ago 105
Java Question

adding multiple entries to a HashMap at once in one statement

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],

I have not found any example that shows how to do this having looked at so many ...

Many thanks

Answer Source

You can do this:

Map<String, Integer> hashMap = new HashMap<String, Integer>()
     put("One", 1);
     put("Two", 2);
     put("Three", 3);