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],
nil]
I have not found any example that shows how to do this having looked at so many.
你可以这样做:
Map<String, Integer> hashMap = new HashMap<String, Integer>()
{{
put("One", 1);
put("Two", 2);
put("Three", 3);
}};
You 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):
import com.google.common.collect.ImmutableMap;
// For up to five entries, use .of()
Map<String, Integer> littleMap = ImmutableMap.of(
"One", Integer.valueOf(1),
"Two", Integer.valueOf(2),
"Three", Integer.valueOf(3)
);
// For more than five entries, use .builder()
Map<String, Integer> bigMap = ImmutableMap.<String, Integer>builder()
.put("One", Integer.valueOf(1))
.put("Two", Integer.valueOf(2))
.put("Three", Integer.valueOf(3))
.put("Four", Integer.valueOf(4))
.put("Five", Integer.valueOf(5))
.put("Six", Integer.valueOf(6))
.build();
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?
In Java 9, it is possible to use Map.of(...)
, like so:
Map<String, Integer> immutableMap = Map.of("One", 1, "Two", 2, "Three", 3);
This map is immutable. If you want the map to be mutable, you have to add:
Map<String, Integer> hashMap = new HashMap<>(immutableMap);
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.
链接地址: http://www.djcxy.com/p/82400.html上一篇: 用一些预定义值初始化ArrayList