Java ArrayList and HashMap on-the-fly

Viewed 58712

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' );
8 Answers
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");

Arrays can be converted to Lists:

List<String> al = Arrays.asList("vote", "for", "me"); //pandering

Note that this does not return an ArrayList but an arbitrary List instance (in this case it’s an Array.ArrayList)!

Bruno's approach works best and could be considered on the fly for maps. I prefer the other method for lists though (seen above):

Map<String,String> map = new HashMap<String,String>() {
 {
    put("key1", "value1");
    put("key2", "value2");
 }
};

for short lists:

    List<String> ab = Arrays.asList("a","b");

Use a nice anonymous initializer:

List<String> list = new ArrayList<String>() {{
    add("a");
    add("b");
}};

Same goes for a Map:

Map<String, String> map = new HashMap<String, String>() {{
    put("a", "a");
    put("b", "b");
}};

I find this the most elegant and readable.

Other methods demand creating an array first, then converting it to a List - too expensive in my taste, and less readable.

You mean like this?

public List<String> buildList(String first, String second)
{
     List<String> ret = new ArrayList<String>();
     ret.add(first);
     ret.add(second);
     return ret;
}

...

List<String> names = buildList("Jon", "Marc");

Or are you interested in the ArrayList constructor which takes a Collection<? extends E>? For example:

String[] items = new String[] { "First", "Second", "Third" };
// Here's one way of creating a List...
Collection<String> itemCollection = Arrays.asList(items);
// And here's another
ArrayList<String> itemList = new ArrayList<String>(itemCollection);

How about this?

ArrayList<String> array = new ArrayList<String>(Arrays.asList("value1", "value2"));

I know many of the answers provided similar solutions, but I think this one is a little more exact and more succinct. If you have lots of values, you might wanna do this:

ArrayList<String> array = new ArrayList<String>(Arrays.asList(
    "value1",
    "value2",
    "value3",
    ...
));
Related