Skip to content

Commit b28e647

Browse files
committed
feat: 添加用于快速创建 map 的 MapUtil 及测试类
1 parent 0dde055 commit b28e647

2 files changed

Lines changed: 89 additions & 0 deletions

File tree

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package info.cadecode.simple.util;
2+
3+
import java.util.LinkedHashMap;
4+
import java.util.Map;
5+
6+
/**
7+
* @author Cade Li
8+
* @date 2021/7/18
9+
* @description: 链式调用的 map 工具类
10+
*/
11+
public class MapUtil {
12+
13+
public static MapBuilder<String, Object> create() {
14+
return new MapBuilder<String, Object>(new LinkedHashMap<>());
15+
}
16+
17+
public static <K, V> MapBuilder<K, V> create(Map<K, V> map) {
18+
return new MapBuilder<K, V>(map);
19+
}
20+
21+
public static class MapBuilder<K, V> {
22+
23+
private Map<K, V> map;
24+
25+
/**
26+
* 私有构造
27+
*/
28+
private MapBuilder(Map<K, V> map) {
29+
this.map = map;
30+
}
31+
32+
/**
33+
* 链式添加
34+
*/
35+
public MapBuilder<K, V> add(K k, V v) {
36+
map.put(k, v);
37+
return this;
38+
}
39+
40+
/**
41+
* 链式删除
42+
*/
43+
public MapBuilder<K, V> del(K k) {
44+
map.remove(k);
45+
return this;
46+
}
47+
48+
/**
49+
* 转外 map
50+
*/
51+
public Map<K, V> asMap() {
52+
return map;
53+
}
54+
55+
/**
56+
* 转外 map
57+
*/
58+
public String asJson() {
59+
return JsonUtil.objToStr(map);
60+
}
61+
62+
private void setMap(Map<K, V> map) {
63+
this.map = map;
64+
}
65+
}
66+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package info.cadecode.simple.util;
2+
3+
import info.cadecode.simple.SimpleSpringBootApplicationTests;
4+
import org.junit.jupiter.api.Test;
5+
6+
import java.util.HashMap;
7+
8+
/**
9+
* @author Cade Li
10+
* @date 2021/7/18
11+
* @description:
12+
*/
13+
public class MapUtilTest extends SimpleSpringBootApplicationTests {
14+
15+
@Test
16+
public void add() {
17+
String json = MapUtil.create(new HashMap<String, Integer>())
18+
.add("a", 1)
19+
.add("b", 2)
20+
.asJson();
21+
log.info("json: {}", json);
22+
}
23+
}

0 commit comments

Comments
 (0)