有没有这样初始化Java HashMap的方法?:
Map<String,String> test =
new HashMap<String, String>{"test":"test","test":"test"};
正确的语法是什么?我没有发现任何与此相关的信息。这可能吗?我正在寻找最短/最快的方法来将一些“最终/静态”值放在地图中,这些值永远不会改变,并且在创建地图时预先知道。
有没有这样初始化Java HashMap的方法?:
Map<String,String> test =
new HashMap<String, String>{"test":"test","test":"test"};
正确的语法是什么?我没有发现任何与此相关的信息。这可能吗?我正在寻找最短/最快的方法来将一些“最终/静态”值放在地图中,这些值永远不会改变,并且在创建地图时预先知道。
当前回答
JAVA 8
在普通的java8中,您还可以使用Streams/Collectors来完成这项工作。
Map<String, String> myMap = Stream.of(
new SimpleEntry<>("key1", "value1"),
new SimpleEntry<>("key2", "value2"),
new SimpleEntry<>("key3", "value3"))
.collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue));
这具有不创建匿名类的优点。
请注意,进口产品包括:
import static java.util.stream.Collectors.toMap;
import java.util.AbstractMap.SimpleEntry;
当然,正如在其他答案中所指出的,在java9之后,您有更简单的方法来实现同样的目的。
其他回答
使用Java 8或更低版本
您可以使用静态块用一些值初始化映射。例子:
public static Map<String,String> test = new HashMap<String, String>
static {
test.put("test","test");
test.put("test1","test");
}
使用Java 9或更高版本
在声明时,可以使用Map.of()方法用一些值初始化映射。例子:
public static Map<String,String> test = Map.of("test","test","test1","test");
另一种方法是使用纯Java 7类和varargs:使用以下方法创建一个类HashMapBuilder:
public static HashMap<String, String> build(String... data){
HashMap<String, String> result = new HashMap<String, String>();
if(data.length % 2 != 0)
throw new IllegalArgumentException("Odd number of arguments");
String key = null;
Integer step = -1;
for(String value : data){
step++;
switch(step % 2){
case 0:
if(value == null)
throw new IllegalArgumentException("Null key value");
key = value;
continue;
case 1:
result.put(key, value);
break;
}
}
return result;
}
使用如下方法:
HashMap<String,String> data = HashMapBuilder.build("key1","value1","key2","value2");
of()似乎最普遍,也最不受限制。这里,它自动处理非对象输入值:
List<Map<String, Object> certs = new ArrayList<>(){{ add( Map.of(
"TAG", Obj1 // Object
"TAGGED_ID", 1L //Long
"DEGREE", "PARENT" // String
"DATE", LocalDate.now() // LocalDate
));}};
注意,由静态Map.of(..)构造函数创建的映射不允许键和值都为空。
您可以通过两种简单的方式轻松地创建自己的Map.of(仅在Java9及更高版本中可用)方法
使用设定数量的参数
实例
public <K,V> Map<K,V> mapOf(K k1, V v1, K k2, V v2 /* perhaps more parameters */) {
return new HashMap<K, V>() {{
put(k1, v1);
put(k2, v2);
// etc...
}};
}
使用列表制作
您也可以使用列表来实现这一点,而不是为某一组参数创建许多方法。
实例
public <K, V> Map<K, V> mapOf(List<K> keys, List<V> values) {
if(keys.size() != values.size()) {
throw new IndexOutOfBoundsException("amount of keys and values is not equal");
}
return new HashMap<K, V>() {{
IntStream.range(0, keys.size()).forEach(index -> put(keys.get(index), values.get(index)));
}};
}
笔记不建议将其用于所有对象,因为每次使用时都会生成一个匿名类。
执行此操作的简单方法:
public static Map<String, String> mapWithValues(String...values) {
Map<String, String> map = new HashMap<String, String>();
for (int x = 0; x < values.length; x = x+2) {
map.put(values[x], values[x+1]);
}
return map;
}