将两个列表组合成地图(Java)的最佳方法是什么? [英] What is the best way to combine two lists into a map (Java)?
问题描述
使用 for (String item: list)
会很好,但它只会遍历一个列表,并且您需要一个显式迭代器用于另一个列表.或者,您可以对两者都使用显式迭代器.
It would be nice to use for (String item: list)
, but it will only iterate through one list, and you'd need an explicit iterator for the other list. Or, you could use an explicit iterator for both.
这是问题的一个示例,以及使用索引 for
循环代替的解决方案:
Here's an example of the problem, and a solution using an indexed for
loop instead:
import java.util.*;
public class ListsToMap {
static public void main(String[] args) {
List<String> names = Arrays.asList("apple,orange,pear".split(","));
List<String> things = Arrays.asList("123,456,789".split(","));
Map<String,String> map = new LinkedHashMap<String,String>(); // ordered
for (int i=0; i<names.size(); i++) {
map.put(names.get(i), things.get(i)); // is there a clearer way?
}
System.out.println(map);
}
}
输出:
{apple=123, orange=456, pear=789}
有更清楚的方法吗?也许在某个地方的集合 API 中?
Is there a clearer way? Maybe in the collections API somewhere?
推荐答案
由于键值关系是通过列表索引隐式的,我认为显式使用列表索引的 for-loop 解决方案实际上非常清晰 - 并且简短
Since the key-value relationship is implicit via the list index, I think the for-loop solution that uses the list index explicitly is actually quite clear - and short as well.
这篇关于将两个列表组合成地图(Java)的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!