Java ArrayList and HashMap on-the-fly

JavaCollections

Java Problem Overview


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' );

Java Solutions


Solution 1 - Java

List<String> list = new ArrayList<String>() {
 {
    add("value1");
    add("value2");
 }
};

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

Solution 2 - Java

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");

Solution 3 - Java

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");
 }
};

Solution 4 - Java

for short lists:

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

Solution 5 - Java

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.

Solution 6 - Java

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

Solution 7 - Java

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

Solution 8 - Java

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",
    ...
));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSteve MView Question on Stackoverflow
Solution 1 - Javabruno condeView Answer on Stackoverflow
Solution 2 - JavaSteve McLeodView Answer on Stackoverflow
Solution 3 - JavacgpView Answer on Stackoverflow
Solution 4 - JavaAndreas PeterssonView Answer on Stackoverflow
Solution 5 - JavaYuval AdamView Answer on Stackoverflow
Solution 6 - JavaR. OosterholtView Answer on Stackoverflow
Solution 7 - JavaJon SkeetView Answer on Stackoverflow
Solution 8 - JavaahmadPHView Answer on Stackoverflow