views:

147

answers:

4

Possible Duplicate:
Clearest way to combine two lists into a map (Java)?

Given this:

    List<Integer> integers = new ArrayList<Integer>();
    List<String> strings = new ArrayList<String>();

    strings.add("One");
    strings.add("Two");
    strings.add("Three");

    integers.add(new Integer(1));
    integers.add(new Integer(2));
    integers.add(new Integer(3));

What is the best way to merge these lists into a map like ["One" => 1, "Two" => 2, "Three"=>3]?

Thanks for any suggestions

+9  A: 

Assuming, that both lists are of equal length and that keys and values have the same index in both lists, then this is an easy approach:

for (int i = 0; i < strings.size(); i++) {
  map.put(strings.get(i), integers.get(i));
}
Andreas_D
Thanks, was thinking there might be a method somewhere in the java library to do it, but I suppose thats concise enough!
Chris
Hope you don't get given `LinkedList`s. (But then if you are using `LinkedList` performance is probably off anyway.)
Tom Hawtin - tackline
Would iterators make it LinkedList-friendly?
Chris
@Chris: Yes, it would. Wait, I'll add it as an answer.
missingfaktor
+3  A: 

Something like:

HashMap<String,Integer> hmap=new HashMap<String,Integer>();

for (int i=0; i<strings.size(); i++) {
  hmap.put(strings.get(i),integers.get(i));
}
mikera
+1  A: 

Over here in Scala land, we'd write it as:

integers.zip(strings).toMap

:-P

Muhaha
+1  A: 

Code suggested by Andreas or Mikera is fine as long as the List implementation you are using has an efficient get method. There may be cases where access by index is rather expensive (for example, LinkedList).

That's why, in general, you should prefer iterators for such procedures.

Code:

Iterator<String> stringsItr = strings.iterator();
Iterator<Integer> integersItr = integers.iterator();
Map<String, Integer> map = new HashMap<String, Integer>();
while(stringsItr.hasNext() && integers.hasNext()) {
  map.put(stringsItr.next(), integers.next());
}
missingfaktor
what if `stringsItr.hasNext()` returns `true` and `integers.hasNext()` returns `false`? Ouch.
Noel M
missingfaktor