最清晰的方式将两个列表组合到一个映射(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.
下面是一个问题的例子,以及一个使用索引代替$ c的解决方案$ c> loop:
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?
答
由于键值关系是通过列表索引隐式的,明确使用列表索引的循环解决方案实际上是相当清楚的 - 也很短。
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.