通过Builder来构建集合list和map

之前已经写过一篇通用Builder来构建实例对象的(基于Java8的新特性写一个通用的Builder工具类_java手动写一个builder-CSDN博客)但是这个builder不能构建集合,也就是list和map,今天突然心血来潮,想写写集合类的builder,这两个builder相比于通用的builder要简单易懂的多,废话不多说,直接上代码:

Mapbuilder:

public class MapBuilder {
    private Map map;

    private MapBuilder(Map map) {
        this.map = map;
    }

    public static  MapBuilder ofMap() {
        return new MapBuilder<>(new HashMap());
    }

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

    public Map build() {
        return this.map;
    }

    public static void main(String[] args) {
        Map map = MapBuilder.ofMap()
                .put("a", 1)
                .put("b", 2)
                .put("c", 3)
                .build();

        System.out.println(map); // 输出:{a=1, b=2, c=3}
    }
}

ListBuilder:

public class ListBuilder {
    private List list;

    private ListBuilder(List list) {
        this.list = list;
    }

    public static  ListBuilder ofList() {
        return new ListBuilder(new ArrayList());
    }

    public ListBuilder add(T t) {
        this.list.add(t);
        return this;
    }

    public List build() {
        return this.list;
    }

    public static void main(String[] args) {
        List integers = ListBuilder.ofList().add(1).build();
        System.err.println(integers);
    }
}

你可能感兴趣的:(list)