Java ArrayList and HashMap on-the-fly

后端 未结 7 1129
甜味超标
甜味超标 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<String> stringList = Arrays.asList("one", "two");
    List<Integer> intList = Arrays.asList(1, 2);
    

    For Maps you could use this:

    public static <K, V> Map<K, V> mapOf(Object... keyValues) {
        Map<K, V> 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<Integer, String> map1 = mapOf(1, "value1", 2, "value2");
    Map<String, String> 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

    0 讨论(0)
提交回复
热议问题