当前位置: 首页 > 工具软件 > Mapbuilder > 使用案例 >

MapBuilder(java map构建器)

薛楷
2023-12-01

自己写的Map构建器,更方便的操作map

public static void main(String[] args) {
        Map<Object, Object> map = MapBuilder.builder().put("1", 1).put("2", 2).put("3", 3).build();
        System.out.println(map);

        Map<String, Integer> map1 = MapBuilder.<String, Integer>builder().put("1", 1).put("2", 2).put("3", 3).build();
        System.out.println(map1);

        Map<String, Integer> map2 = MapBuilder.<String, Integer>builder(new LinkedHashMap<>(16)).put("1", 1).put("2", 2).put("3", 3).build();
        System.out.println(map2);
    }


import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @className MapBuilder.java
 * @author xzy
 * @version 1.0.0
 * @description Map构建器
 * @createTime 2022年09月28日 15:50:00
 */
public class MapBuilder<K, V> {

    private final Map<K, V> map;

    private MapBuilder(Map<K, V> map) {
        this.map = Objects.isNull(map) ? new HashMap<>(16) : map;
    }

    public static <K, V> MapBuilder<K, V> builder() {
        return builder(null);
    }

    public static <K, V> MapBuilder<K, V> builder(Map<K, V> map) {
        return new MapBuilder<K, V>(map);
    }

    public MapBuilder<K, V> put(K key, V value) {
        this.map.put(key, value);
        return this;
    }

    public Map<K, V> build() {
        return this.map;
    }
}

 类似资料: