builder for HashMap

前端 未结 15 2240
迷失自我
迷失自我 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条回答
  •  执笔经年
    2020-11-30 01:00

    Here is a very simple one ...

    public class FluentHashMap extends java.util.HashMap {
      public FluentHashMap with(K key, V value) {
        put(key, value);
        return this;
      }
    
      public static  FluentHashMap map(K key, V value) {
        return new FluentHashMap().with(key, value);
      }
    }
    

    then

    import static FluentHashMap.map;
    
    HashMap m = map("a", 1).with("b", 2);
    

    See https://gist.github.com/culmat/a3bcc646fa4401641ac6eb01f3719065

提交回复
热议问题