问题描述
使用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}
有更清晰的方法吗?也许在Collections API中的某个地方?
Is there a clearer way? Maybe in the collections API somewhere?
推荐答案
由于键值关系通过列表索引是隐式的,因此我认为显式使用列表索引的for循环解决方案非常清晰-且简短也是
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)中的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!