Can someone please provide an example of creating a Java ArrayList
and HashMap
on the fly? So instead of doing an add()
or put()
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