1

I have two ArrayLists:

ArrayList<Integer> keySet = new ArrayList<Integer>();

and

ArrayList<String> values = new ArrayList<String>();

How would I create a HashMap using the keySet ArrayList as the keyset in the hashmap and the values ArrayList as the values in the HashMap?

1
  • 1
    Be careful, the question smells a little bit of misunderstanding HashMap. A key is always associated with the value you give it. The answer below will associate them by their index order, but any modifications after that and the two collections will diverge. HashMap alone also does not preserve order, your keys won't necessarily print in the same order you put them in. Commented Aug 14, 2019 at 20:16

1 Answer 1

3

Assuming the length is the same:

HashMap<Integer, String> a = new HashMap<>();
for(int i = 0; i < keySet.size(); i++) {
    a.put(keySet.get(i), values.get(i));
}
Sign up to request clarification or add additional context in comments.

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.