方式1:匿名内部类
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class MapUtilTest {
@Test
public void test() {
Map<String, String> map = new HashMap<String, String>(){{
put("k1", "v1");
put("k2", "v2");
}};
System.out.println(map);
}
}
运行结果:
{k1=v1, k2=v2}
方式2:自定义工具方法
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class MapUtil {
public static class Entry<K,V> {
private K key;
private V val;
public Entry(K key, V val) {
this.key = key;
this.val = val;
}
public K getKey() {
return this.key;
}
public V getVal() {
return this.val;
}
}
public static <K, V> Entry<K, V> kv(K key, V val) {
return new Entry<K, V>(key, val);
}
public static <K, V> Map<K, V> map(Entry<K, V>... data) {
return concurrentHashMap(data);
}
public static <K, V> HashMap<K, V> hashMap(Entry<K, V>... entries){
HashMap<K, V> result = new HashMap<K, V>();
putEntriesIntoMap(result, entries);
return result;
}
public static <K, V> ConcurrentHashMap<K, V> concurrentHashMap(Entry<K, V>... entries){
ConcurrentHashMap<K, V> result = new ConcurrentHashMap<K, V>();
putEntriesIntoMap(result, entries);
return result;
}
private static <K, V> void putEntriesIntoMap(Map<K,V> map, Entry<K, V>[] entries) {
for(Entry<K, V> item : entries){
map.put(item.getKey(), item.getVal());
}
}
}
import org.junit.Test;
import java.util.Map;
import static MapUtil.kv;
public class MapUtilTest {
@Test
public void test() {
Map<String, String> map = MapUtil.hashMap(
kv("k1", "v1"),
kv("k2", "v2")
);
System.out.println(map);
}
}
运行结果:
{k1=v1, k2=v2}