使用hashmap判断是否包含某个元素

测试

在日常开发中,经常用到某个字段是否存在的遍历,hashmap将key换算成hash值作为数组的索引,速度更快,今天无聊,故写个文章。

for循环遍历查询包含某个字符串的平均耗时为 80 单位时间
hashmap查询包含某个字符串的平均耗时为 35 单位时间
综上,在实际应用中,hashmap是检验是否包含字符串的高效方式之一。

import java.util.ArrayList;
import java.util.HashMap;

public class Test03 {
    public static void main(String[] args) {
        HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
        stringIntegerHashMap.put("雨JL",1);
        stringIntegerHashMap.put("雨lgjlgh",1);
        stringIntegerHashMap.put("J",1);
        stringIntegerHashMap.put("雨D",1);
        stringIntegerHashMap.put("雨G",1);
        stringIntegerHashMap.put("雨B",1);
        stringIntegerHashMap.put("D雨",1);
        stringIntegerHashMap.put("雨H",1);
        stringIntegerHashMap.put("雨DG",1);
        stringIntegerHashMap.put("雨GHH",1);
        stringIntegerHashMap.put("雨F",1);

        ArrayList<String> strings= new ArrayList<>();
        strings.add("雨JL");
        strings.add("雨lgjlgh");
        strings.add("J");
        strings.add("雨D");
        strings.add("雨G");
        strings.add("雨B");
        strings.add("D雨");
        strings.add("雨H");
        strings.add("雨DG");
        strings.add("雨GHH");
        strings.add("雨F");
        
        int flag = 0 ;
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            forMethod(flag, strings , "雨F");
        }
        long timeComsumed1 = System.currentTimeMillis()-start;
        System.out.println(timeComsumed1);

			 flag = 0;
        start = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            hashMapMethod(flag, stringIntegerHashMap , "雨F");
        }
        long timeComsumed2 = System.currentTimeMillis()-start;
        System.out.println(timeComsumed2);

        System.out.println(timeComsumed2- timeComsumed1);
    }

    public static void forMethod (int flag ,ArrayList<String> arrayList, String str){
        for (String s : arrayList) {
            if(str == s){
                flag = 1;
                return;
            }
        }
    }

    public static void hashMapMethod (int flag , HashMap<String,Integer> map, String str){
        if ( map.containsKey(str)){
            flag = 1;
            return;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值