EntrySet与KeySet遍历Map及性能对比

本文探讨了在Java中遍历Map时,使用EntrySet和KeySet两种方法的性能差异。通过代码示例展示了两种遍历方式,并在Map包含1百万条数据的情况下进行了耗时对比,结果显示EntrySet遍历速度快于KeySet,原因是EntrySet直接提供key-value对,避免了额外的遍历操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Map作为Java的一个基本集合类,在很多场所都会使用到它。在使用Map时,会经常会遇到需要遍历整个Map情况。遍历Map时,主要使用的是EntrySet以及KeySet这两种遍历方法。
以下是实现两种遍历方式的代码:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 遍历Map
 */
public class IterateMapDemo {

    /**
     * 主函数
     * @param args
     */
    public static void main(String[] args) {
        Map<String, String> areaMap = new HashMap<String, String>();
        areaMap.put("Beijing", "北京");
        areaMap.put("Shanghai", "上海");
        areaMap.put("Tianjin", "天津");

        // 遍历
        keySetIterateMap(areaMap);
        entrySetIterateMap(areaMap);
    }

    /**
     * keySet方式遍历
     * @param mapInfo
     */
    private static void keySetIterateMap(Map<String, String> mapInfo) {
        // for循环遍历
        Set<String> keySet = mapInfo.keySet();
        for (String key : keySet) {
            System.out.println("KeySet,For循环遍历,Key:" + key + "Value:" + mapInfo.get(key));
        }

        // 迭代器遍历
        Iterator<String> it = mapInfo.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            System.out.println("KeySet,Iterator遍历,Key:" + key + "Value:" + mapInfo.get(key));
        }
    }

    /**
     * entrySet遍历
     * @param mapInfo
     */
    private static void entrySetIterateMap(Map<String, String> mapInfo) {
        // for循环遍历
        Set<Map.Entry<String, String>> entrySet = mapInfo.entrySet();
        for (Map.Entry<String, String> entry : entrySet) {
            System.out.println("EntrySet,For循环遍历,Key:" + entry.getKey() + "Value:" + entry.getValue());
        }

        // 迭代器遍历
        Iterator<Map.Entry<String, String>> it = mapInfo.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            System.out.println("EntrySet,Iterator循环遍历,Key:" + entry.getKey() + "Value:" + entry.getValue());
        }
    }
}

性能对比
在数据量少的时候,两种遍历自然差距不会太大。但是当数据量增加的时候,就需要对比下哪种遍历方式更快了。
以下是Map中具有1百万条数据时,两种遍历方式的耗时信息(单位ms):

可以看出,EntrySet遍历的速度要比keySet方法要快哦。这是因为使用keySet遍历时,当使用key值取得Map中的Value时,Map又遍历了一遍。而EntrySe时,由于EntrySet本身就是key-value结构,所以直接将Map的key-value给取出来了,自然速度就要快上一些。另外,使用迭代器遍历的话速度也会有一些提升。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值