Java ArrayList and HashMap on-the-fly

后端 未结 7 1322
甜味超标
甜味超标 2021-01-31 07:07

Can someone please provide an example of creating a Java ArrayList and HashMap on the fly? So instead of doing an add() or put()

7条回答
  •  感动是毒
    2021-01-31 08:01

    For lists you can use Arrays.asList like this:

    List stringList = Arrays.asList("one", "two");
    List intList = Arrays.asList(1, 2);
    

    For Maps you could use this:

    public static  Map mapOf(Object... keyValues) {
        Map map = new HashMap<>();
    
        K key = null;
        for (int index = 0; index < keyValues.length; index++) {
            if (index % 2 == 0) {
                key = (K)keyValues[index];
            }
            else {
                map.put(key, (V)keyValues[index]);
            }
        }
    
        return map;
    }
    
    Map map1 = mapOf(1, "value1", 2, "value2");
    Map map2 = mapOf("key1", "value1", "key2", "value2");
    

    Note: in Java 9 you can use Map.of
    Note2: Double Brace Initialization for creating HashMaps as suggested in other answers has it caveats

提交回复
热议问题