遍历map集合快捷方式
时间: 2023-11-11 19:00:50 浏览: 40
可以使用C++11中的range-based for循环来遍历map集合,示例代码如下:
```c++
std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
for (const auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
```
输出结果为:
```
1: one
2: two
3: three
```
相关问题
遍历map集合的集中方式
1. 使用 for-each 循环遍历 Map 的键或值:
```java
Map<String, Integer> map = new HashMap<>();
for (String key : map.keySet()) {
Integer value = map.get(key);
System.out.println(key + " = " + value);
}
for (Integer value : map.values()) {
System.out.println(value);
}
```
2. 使用迭代器遍历 Map 的键或值:
```java
Iterator<String> keyIterator = map.keySet().iterator();
while (keyIterator.hasNext()) {
String key = keyIterator.next();
Integer value = map.get(key);
System.out.println(key + " = " + value);
}
Iterator<Integer> valueIterator = map.values().iterator();
while (valueIterator.hasNext()) {
Integer value = valueIterator.next();
System.out.println(value);
}
```
3. 使用 Java 8 中的 Stream API 遍历 Map:
```java
map.forEach((key, value) -> System.out.println(key + " = " + value));
map.keySet().stream().forEach(key -> {
Integer value = map.get(key);
System.out.println(key + " = " + value);
});
map.values().stream().forEach(value -> System.out.println(value));
```
koltin遍历map集合
在 Kotlin 中,遍历 Map 集合可以使用以下几种方式:
1. 使用 for 循环遍历 Map 集合的键值对:
```kotlin
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
for ((key, value) in map) {
println("key = $key, value = $value")
}
```
2. 使用 forEach() 方法遍历 Map 集合的键值对:
```kotlin
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
map.forEach { (key, value) ->
println("key = $key, value = $value")
}
```
3. 遍历 Map 集合的键或值:
```kotlin
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
for (key in map.keys) {
println("key = $key")
}
for (value in map.values) {
println("value = $value")
}
```
以上是 Kotlin 遍历 Map 集合的几种方式,根据实际需求选择合适的方式即可。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)