collection集合与map集合可以使用interator
时间: 2023-06-12 16:05:21 浏览: 63
是的,Collection和Map都可以使用Iterator来遍历集合中的元素。
对于Collection集合,使用iterator()方法获取Iterator对象,然后使用hasNext()和next()方法遍历元素,例如:
```
List<String> list = new ArrayList<>();
list.add("apple");
list.add("orange");
list.add("banana");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
```
对于Map集合,使用entrySet()方法获取Map.Entry集合,然后使用iterator()方法获取Iterator对象,遍历每个键值对,例如:
```
Map<String, String> map = new HashMap<>();
map.put("name", "Tom");
map.put("age", "18");
map.put("gender", "male");
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println(entry.getKey() + ": " + entry.getValue());
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)