使用for(String item:list)会很好,但是它只会迭代一个列表,而你需要一个显式迭代器用于另一个列表.或者,您可以为两者使用显式迭代器.
以下是问题的示例,以及使用索引for循环的解决方案:
import java.util.*;
public class ListsToMap {
static public void main(String[] args) {
List names = Arrays.asList("apple,orange,pear".split(","));
List things = Arrays.asList("123,456,789".split(","));
Map map = new LinkedHashMap(); // ordered
for (int i=0; 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?
解决方法:
由于键值关系是通过列表索引隐式的,我认为明确使用列表索引的for循环解决方案实际上非常清楚 – 也很短.
标签:java,collections,data-structures
来源: https://codeday.me/bug/20190916/1808594.html