builder for HashMap

前端 未结 15 2275
迷失自我
迷失自我 2020-11-30 00:17

Guava provides us with great factory methods for Java types, such as Maps.newHashMap().

But are there also builders for java Maps?

HashM         


        
15条回答
  •  猫巷女王i
    2020-11-30 00:46

    Here's one I wrote

    import java.util.Collections;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.function.Supplier;
    
    public class MapBuilder {
    
        private final Map map;
    
        /**
         * Create a HashMap builder
         */
        public MapBuilder() {
            map = new HashMap<>();
        }
    
        /**
         * Create a HashMap builder
         * @param initialCapacity
         */
        public MapBuilder(int initialCapacity) {
            map = new HashMap<>(initialCapacity);
        }
    
        /**
         * Create a Map builder
         * @param mapFactory
         */
        public MapBuilder(Supplier> mapFactory) {
            map = mapFactory.get();
        }
    
        public MapBuilder put(K key, V value) {
            map.put(key, value);
            return this;
        }
    
        public Map build() {
            return map;
        }
    
        /**
         * Returns an unmodifiable Map. Strictly speaking, the Map is not immutable because any code with a reference to
         * the builder could mutate it.
         *
         * @return
         */
        public Map buildUnmodifiable() {
            return Collections.unmodifiableMap(map);
        }
    }
    

    You use it like this:

    Map map = new MapBuilder(LinkedHashMap::new)
        .put("event_type", newEvent.getType())
        .put("app_package_name", newEvent.getPackageName())
        .put("activity", newEvent.getActivity())
        .build();
    

提交回复
热议问题