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

后端 未结 14 2596
野趣味
野趣味 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

    You could possibly make your own Map.of (which is only available in Java 9 and higher) method easily in 2 easy ways

    Make it with a set amount of parameters

    Example

    public  Map mapOf(K k1, V v1, K k2, V v2 /* perhaps more parameters */) {
        return new HashMap() {{
          put(k1, v1);
          put(k2,  v2);
          // etc...
        }};
    }
    

    Make it using a List

    You can also make this using a list, instead of making a lot of methods for a certain set of parameters.

    Example

    public  Map mapOf(List keys, List values) {
       if(keys.size() != values.size()) {
            throw new IndexOutOfBoundsException("amount of keys and values is not equal");
        }
    
        return new HashMap() {{
            IntStream.range(0, keys.size()).forEach(index -> put(keys.get(index), values.get(index)));
        }};
    }
    

    Note It is not recommended to use this for everything as this makes an anonymous class every time you use this.

提交回复
热议问题