方式1:匿名内部类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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);
}

}

运行结果:

1
{k1=v1, k2=v2}

方式2:自定义工具方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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());
}
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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);
}

}

运行结果:

1
{k1=v1, k2=v2}