2

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?

1
  • 3
    No, this will only put one entry into the map. You'll need to iterate through both lists, and put the entries in individually. Commented Feb 25, 2014 at 4:08

2 Answers 2

2

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));
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.