Java ArrayList and HashMap on-the-fly
Can someone please provide an example of creating a Java ArrayList
and HashMap
on the fly? So instead of doing an add()
or put()
, actually supplying the seed data for the array/hash at the class instantiation?
To provide an example, something similar to PHP for instance:
$array = array (3, 1, 2);
$assoc_array = array( 'key' => 'value' );
List<String> list = new ArrayList<String>() {
{
add("value1");
add("value2");
}
};
Map<String,String> map = new HashMap<String,String>() {
{
put("key1", "value1");
put("key2", "value2");
}
};
A nice way of doing this is using List.of()
and Map.of()
(since Java 8):
List<String> list = List.of("A", "B", "C");
Map<Integer, String> map = Map.of(1, "A",
2, "B",
3, "C");
Java 7 and earlier may use Google Collections:
List<String> list = ImmutableList.of("A", "B", "C");
Map<Integer, String> map = ImmutableMap.of(
1, "A",
2, "B",
3, "C");