curious_cat
curious_cat

Reputation: 906

Creating HashMap from ArrayList

I have two ArrayList of string and want to merge them into a single hashmap. I am doing something like this.

HashMap<ArrayList<String>,ArrayList<String>> map = new HashMap<ArrayList<String>, ArrayList<String>>();

ArrayList<String>k =  receivedIntent.getStringArrayListExtra("keys");
ArrayList<String>v = receivedIntent.getStringArrayListExtra("values");

map.put(k, v);

Is this the right way? Ideally I want to access values in v array using values in k array as keys in the hashmap like value = map.get("Name"), where Name is one of the keys?

Upvotes: 2

Views: 8617

Answers (2)

Cruceo
Cruceo

Reputation: 6824

First of all, we're making the assumption that both k and v will be of equal length AND that keys will be unique. You may want to surround the mapping with a try/catch block.

HashMap<String, String> map = new HashMap<String, String>();

ArrayList<String>k =  receivedIntent.getStringArrayListExtra("keys");
ArrayList<String>v = receivedIntent.getStringArrayListExtra("values");

for(int i = 0; i < k.size(); i++) map.put(k.get(i), v.get(i));

Upvotes: 2

flx
flx

Reputation: 14226

Assuming both Lists are of the same length and you want to have the elements as key value pair:

ArrayList<String> k =  receivedIntent.getStringArrayListExtra("keys");
ArrayList<String> v = receivedIntent.getStringArrayListExtra("values");
HashMap<String,String> map = new HashMap<String, String>();
for (int i = 0; i < k.size() && i < v.size(); ++i) {
  // putting each element of k/v into the map
  map.put(k.get(i), v.get(i));
}

Upvotes: 1

Related Questions