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 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