vulturistic vulturistic - 2 years ago 137
Java Question

How to put an array object in hashmap?

I'm trying to solve this but I'm stuck here for a while now. My problem is I can't find a way on how to put an array object to my hashmap.

Here's my example code of hashmap for dropdown menu that I got from google.

private Map<String,Map<String,String>> data2 = new HashMap<String,Map<String,String>>();
private String country;
private String city;
private Map<String, String> countries;
private Map<String,String> cities;

countries = new HashMap<String, String>();
countries.put("USA", "USA");
countries.put("Germany", "Germany");
countries.put("Brazil", "Brazil");

Map<String,String> map = new HashMap<String, String>();
map.put("New York", "New York");
map.put("San Francisco", "San Francisco");
map.put("Denver", "Denver");
data2.put("USA", map);

map = new HashMap<String, String>();
map.put("Berlin", "Berlin");
map.put("Munich", "Munich");
map.put("Frankfurt", "Frankfurt");
data2.put("Germany", map);

Now.. My problem is how to put my objects into hashmap.

Here's my code in fetching the array object.

PropertyData reader = new PropertyData();
id = rs.getInt("id");
prop_name = rs.getString("prop_name");
prop_value = rs.getString("prop_value");
engine_name = rs.getString("engine_name");
//other setter..

//other setter..


From the code above. I want to put the id on hashmap key and propname on hashmap string name. Once selected, I want to display other values referencing the id.

And this is where my object has been added.

static List<PropertyData> prop = new ArrayList<PropertyData>();

I tried to initialized it on my hashmap but it returned null.

Answer Source

Ok, you have data in this list:

List<PropertyData> prop = new ArrayList<PropertyData>();

Now, create the map like this (if PropertyData has an unique id - also set size as the size of the array, resizing will be done only once):

HashMap<Integer, PropertyData> map = new HashMap<>(prop.size());

And this is how you place it in the map:

for (PropertyData pd : prop) map.put(pd.getId(), pd);

If id in PropertyData is not unique, create int hashCode() function that will create unique int (based on values in all variables - IDE can create that for you).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download