改造HasMap为链式写法

在工作中 经常会遇到以下这种写法

Map<String, String> hashMap = new HashMap<>();
hashMap.put("id", "xxx");
hashMap.put("name", "xxx");
hashMap.put("age", "xxx");

接下来进行改造 改造成链式的写法

新建一个类 Kv

public class Kv<K, V> extends HashMap<K, V> {
    /**
     * key -> String
     * value -> String
     *
     * @return
     */
    public static Kv<String, String> stringStringKv() {
        return getInstance(String.class, String.class);
    }


    /**
     * key -> string
     * value -> object
     *
     * @return
     */
    public static Kv<String, Object> stringObjectKv() {
        return getInstance(String.class, Object.class);
    }

    /**
     * key -> object
     * value -> object
     *
     * @return
     */
    public static Kv<Object, Object> objectObjectKv() {
        return getInstance(Object.class, Object.class);
    }


    public static <K, V> Kv<K, V> getInstance(Class<? extends K> classKey, Class<? extends V> classValue) {
        return new Kv<K, V>();
    }


    public Kv<K, V> set(K key, V value) {
        put(key, value);
        return this;
    }
}

改造后的 key value 都为String 的写法

Kv<String, String> stringStringKv = Kv.stringStringKv().set("id", "xxx").set("name", "xxx").set("age", "xxx");

改造后的 key 为string value 为Object 写法

Kv<String, Object> stringObjectKv = Kv.stringObjectKv()
        .set(UUID.randomUUID().toString(), new User("张三", 14))
        .set(UUID.randomUUID().toString(), new User("李四", 16));

自定义类型

Kv<String, Integer> stringIntegerKv = Kv.getInstance(String.class, Integer.class);