三种方法遍历Map集合 +遍历Set集合

Map集合的遍历


1、
    public static void work(Map<String, Student> map) {
        Collection<Student> c = map.values();
        Iterator it = c.iterator();
        for (; it.hasNext();) {
            System.out.println(it.next());
        }
    }
2、
    public static void workByKeySet(Map<String, Student> map) {
        Set<String> key = map.keySet();
        for (Iterator it = key.iterator(); it.hasNext();) {
            String s = (String) it.next();
            System.out.println(map.get(s));
        }
    }


3、
 public static void workByEntry(Map<String, Student> map) {
        Set<Map.Entry<String, Student>> set = map.entrySet();
        for (Iterator<Map.Entry<String, Student>> it = set.iterator(); it.hasNext();) {
            Map.Entry<String, Student> entry = (Map.Entry<String, Student>) it.next();
            System.out.println(entry.getKey() + "--->" + entry.getValue());
        }
    }
}
Set 集合的遍历代遍历
1、
Set<String> set = new HashSet<String>();  
Iterator<String> it = set.iterator();  
while (it.hasNext()) {  
  String str = it.next();  
  System.out.println(str);  
}  
2、
for (String str : set) {  
      System.out.println(str);  


### 遍历 C++ 中 `std::map` 的方法 在 C++ 中,可以使用多种方式来遍历 `std::map` 容器中的键值对。以下是几种常见的实现方法: #### 方法一:通过迭代器遍历 这是最经典的方式之一,利用 `std::map::begin()` 和 `std::map::end()` 来获取范围内的所有元素。 ```cpp #include <iostream> #include <map> int main() { std::map<int, std::string> myMap = {{1, "Apple"}, {2, "Banana"}, {3, "Cherry"}}; for (auto it = myMap.begin(); it != myMap.end(); ++it) { std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl; } return 0; } ``` 这种方法适用于任何型的容器,并且性能上与增强型循环相当[^3]。 --- #### 方法二:使用基于范围的 `for` 循环 自 C++11 起引入了更简洁的语法,可以直接访问每个键值对而无需显式声明迭代器。 ```cpp #include <iostream> #include <map> int main() { std::map<int, std::string> myMap = {{1, "Apple"}, {2, "Banana"}, {3, "Cherry"}}; for (const auto& pair : myMap) { std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl; } return 0; } ``` 这种方式不仅代码更加清晰易读,而且编译器优化后其效率也接近于传统迭代器方法。 --- #### 方法三:仅遍历键集或值集 如果只需要处理所有的键或者对应的值,则可以通过调用成员函数 `.key_set()` 或者单独提取每一个组件完成操作。不过需要注意的是,在标准库定义下并没有直接提供这样的接口,因此需手动实现。 ```cpp #include <iostream> #include <map> int main() { std::map<int, std::string> myMap = {{1, "Apple"}, {2, "Banana"}, {3, "Cherry"}}; // 输出所有 Key for (const int &key : myMap.keys()) { std::cout << "Key: " << key << std::endl; } // 如果想打印 Values 可以这样写: for(auto &[k,v] :myMap){ std::cout<<"Value:"<<v<<'\n'; } return 0; } ``` 注意上述例子中最后部分采用结构化绑定特性来自C++17版本以后支持的功能[^4]. --- ### 性能考量 尽管以上各种技术都可以用来枚举关联数组的内容,但从效能角度来看并非全都相同。特别是当涉及到大型数据集合时,“逐一检索并查询”的策略会显得特别低效因为每次寻找都会触发内部哈希计算过程从而增加额外开销。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值