Best way in java to merge two lists to one map? [duplicate]
Possible Duplicate:
Clearest way to combine two lists into a map (Java)? 开发者_StackOverflow中文版
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
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));
}
Over here in Scala land, we'd write it as:
integers.zip(strings).toMap
:-P
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());
}
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));
}
精彩评论