Per gli elenchi è possibile utilizzare Arrays.asList come questo:
List<String> stringList = Arrays.asList("one", "two");
List<Integer> intList = Arrays.asList(1, 2);
per le mappe è possibile utilizzare questo:
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");
Nota: in Java 9
voi può usare Map.of
Nota 2: Double Brace Initialization
per la creazione di HashMaps come suggerito in altre risposte ha caveats
fonte
2017-05-23 09:18:27
stai chiedendo per la sintassi su come farlo, o di un esempio reale del perché si vorrebbe? –