How to directly initialize a HashMap (in a literal way)?

后端 未结 14 2508
野趣味
野趣味 2020-11-22 10:58

Is there some way of initializing a Java HashMap like this?:

Map test = 
    new HashMap{\"test\":\"test\",\"test\         


        
14条回答
  •  自闭症患者
    2020-11-22 11:38

    Unfortunately, using varargs if the type of the keys and values are not the same is not very reasonable as you'd have to use Object... and lose type safety completely. If you always want to create e.g. a Map, of course a toMap(String... args) would be possible though, but not very pretty as it would be easy to mix up keys and values, and an odd number of arguments would be invalid.

    You could create a sub-class of HashMap that has a chainable method like

    public class ChainableMap extends HashMap {
      public ChainableMap set(K k, V v) {
        put(k, v);
        return this;
      }
    }
    

    and use it like new ChainableMap().set("a", 1).set("b", "foo")

    Another approach is to use the common builder pattern:

    public class MapBuilder {
      private Map mMap = new HashMap<>();
    
      public MapBuilder put(K k, V v) {
        mMap.put(k, v);
        return this;
      }
    
      public Map build() {
        return mMap;
      }
    }
    

    and use it like new MapBuilder().put("a", 1).put("b", "foo").build();

    However, the solution I've used now and then utilizes varargs and the Pair class:

    public class Maps {
      public static  Map of(Pair... pairs) {
        Map = new HashMap<>();
    
        for (Pair pair : pairs) {
          map.put(pair.first, pair.second);
        }
    
        return map;
      }
    }
    

    Map map = Maps.of(Pair.create("a", 1), Pair.create("b", "foo");

    The verbosity of Pair.create() bothers me a bit, but this works quite fine. If you don't mind static imports you could of course create a helper:

    public  Pair p(K k, V v) {
      return Pair.create(k, v);
    }
    

    Map map = Maps.of(p("a", 1), p("b", "foo");

    (Instead of Pair one could imagine using Map.Entry, but since it's an interface it requires an implementing class and/or a helper factory method. It's also not immutable, and contains other logic not useful for this task.)

提交回复
热议问题