我想知道为什么没有办法用单个表达式中的值构造一个映射。或者是吗?我期待
new HashMap().add(key, value).add(key, value)...;
即使在 Commons Collections 中我也找不到类似的东西。
我是否错过了 JDK 或 Commons 中的某些方法?
番石榴有它的ImmutableMap
:
final Map<Foo, Bar> map = ImmutableMap.of(foo1, bar1, foo2, bar2, etc, etc);
奖励:ImmutableMap
的名字不是谎言;)
请注意,该方法有 5 个版本.of()
,因此最多有 5 个键/值对。更通用的方法是使用构建器:
final Map<Foo, Bar> map = ImmutableMap.<Foo, Bar>builder()
.put(foo1, bar1)
.put(foo2, bar2)
.put(foo3, bar3)
.put(etc, etc)
.build();
但是请注意:此映射不接受空键或空值。
或者,这是一个穷人版本的ImmutableMap
. 它使用经典的构建器模式。请注意,它不检查空值:
public final class MapBuilder<K, V>
{
private final Map<K, V> map = new HashMap<K, V>();
public MapBuilder<K, V> put(final K key, final V value)
{
map.put(key, value);
return this;
}
public Map<K, V> build()
{
// Return a mutable copy, so that the builder can be reused
return new HashMap<K, V>(map);
}
public Map<K, V> immutable()
{
// Return a copy wrapped into Collections.unmodifiableMap()
return Collections.unmodifiableMap(build());
}
}
然后你可以使用:
final Map<K, V> map = new MapBuilder<K, V>().put(...).put(...).immutable();
试试这个..
Map<String, Integer> map = new HashMap<String, Integer>()
{{
put("One", 1);
put("Two", 2);
put("Three", 3);
}};
Commons Collections 或 JDK 中没有任何内容。但是您也可以使用Guava和以下代码:
Map<String, String> mapInstance = ImmutableMap.<String, String> builder().put("key1", "value1").put("key2", "value2").build();
如果您的钥匙和 vales 是同一类型,那么有这样的方法:
<K> Map<K, K> init(Map<K, K> map, K... args) {
K k = null;
for(K arg : args) {
if(k != null) {
map.put(k, arg);
k = null;
} else {
k = arg;
}
}
return map;
}
您可以使用以下方法初始化地图:
init(new HashMap<String, String>(), "k1", "v1", "k2", "v2");
如果您的钥匙和 vales 是不同的类型,那么有这样的方法:
<K, V> Map<K, V> init(Map<K, V> map, List<K> keys, List<V> values) {
for(int i = 0; i < keys.size(); i++) {
map.put(keys.get(i), values.get(i));
}
return map;
}
您可以使用以下方法初始化地图:
init(new HashMap<String, Integer>(),
Arrays.asList("k1", "k2"),
Arrays.asList(1, 2));