Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' ); 
like image 457
Steve M Avatar asked May 12 '09 13:05

Steve M


People also ask

Can you put an ArrayList in a HashMap?

Array List can be converted into HashMap, but the HashMap does not maintain the order of ArrayList. To maintain the order, we can use LinkedHashMap which is the implementation of HashMap.

Which is faster ArrayList or HashMap?

The ArrayList has O(n) performance for every search, so for n searches its performance is O(n^2). The HashMap has O(1) performance for every search (on average), so for n searches its performance will be O(n). While the HashMap will be slower at first and take more memory, it will be faster for large values of n.

Which is faster list or HashMap?

HashMap is faster than HashSet because the values are associated to a unique key. In HashSet , member object is used for calculating hashcode value which can be same for two objects so equals() method is used to check for equality.

What are the differences between ArrayList and ArrayMap?

ArrayMap is a map (key -> value pairs). ArrayList is a list (a sequence of items). The JavaDoc tells you. It's generally slower but aims to reduce the memory footprint.


2 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");  } }; 
like image 70
bruno conde Avatar answered Sep 23 '22 17:09

bruno conde


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"); 
like image 38
Steve McLeod Avatar answered Sep 21 '22 17:09

Steve McLeod