开发中经常需要创建Map并初始化,Java没有通用便捷的方式,需要依赖第三方库,比如:
Guava
.
为了Map单独引用得不偿失,而且只能初始化少量数据(大概是6对,自己看源码)
简约的工具类
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* 快速创建Map
* @author linyufeng.
* @date 2021/2/3 10:55
**/
public class MapHelper extends HashMap implements Serializable {
public MapHelper() {
}
public MapHelper(Object k, Object v) {
this.add(k, v);
}
public static MapHelper of(Object... args) {
MapHelper map = new MapHelper();
if (args.length % 2 == 1) {
throw new RuntimeException("Args must even, Please check params !");
} else {
for (int i = 0; i < args.length; i += 2) {
map.put(args[i], args[i + 1]);
}
}
return map;
}
public MapHelper add(Object k, Object v) {
this.put(k, v);
return this;
}
}
使用方式:
// 1.快速创建map
Map m1 = MapHelper.of("name","linyufeng","age", 12);
System.out.println(m1.toString());
// 2.构造创建map
Map m2 = new MapHelper(1,2);
System.out.println(m2.toString());
// 3.链式创建map
Map m3 = new MapHelper().add(1,2).add(3,4);
System.out.println(m3.toString());
// 4.混合创建map
Map m4 = MapHelper.of(1,2).add(3,4).add(5,6);
System.out.println(m4.toString());
Map m5 = new MapHelper(1,2).add(3,4).add(5,6);
System.out.println(m5.toString());
结果:
{name=linyufeng, age=12}
{1=2}
{1=2, 3=4}
{1=2, 3=4, 5=6}
{1=2, 3=4, 5=6}