java java中将两个列表合并到一张地图的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3618691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way in java to merge two lists to one map?
提问by Chris
Possible Duplicate:
Clearest way to combine two lists into a map (Java)?
可能的重复:
将两个列表组合成地图的最清晰方法(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]?
将这些列表合并到像 ["One" => 1, "Two" => 2, "Three"=>3] 这样的地图中的最佳方法是什么?
Thanks for any suggestions
感谢您的任何建议
回答by Andreas Dolk
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));
}
回答by Muhaha
Over here in Scala land, we'd write it as:
在 Scala 土地上,我们将其写为:
integers.zip(strings).toMap
:-P
:-P
回答by missingfaktor
Code suggested by Andreas or Mikera is fine as long as the Listimplementation you are using has an efficient getmethod. There may be cases where access by index is rather expensive (for example, LinkedList).
只要List您使用的实现具有有效的get方法,Andreas 或 Mikera 建议的代码就可以。在某些情况下,按索引访问可能会相当昂贵(例如,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());
}
回答by mikera
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));
}

