ArrayList和HashMap遍歷比較

目錄

  • 一、ArrayList遍歷方式
    • 1、普通for循環遍歷
    • 2、增強for循環遍歷
    • 3、Iterator迭代器遍歷
    • 4、三種方式比較
  • 二、Map遍歷方式
    • 1、增強for循環 + keySet() 遍歷
    • 2、增強for循環 + entrySet() 遍歷
    • 3、Iterator + keySet() 遍歷
    • 4、Itorator + entrySet() 遍歷
    • 5、四種方式比較
  • 三、java開發手冊(關于map的)

一、ArrayList遍歷方式

1、普通for循環遍歷

for(int i=0; i<lists.size(); i++){String key = lists.get(i);
}

2、增強for循環遍歷

for(String str : lists){String key = str;
}

3、Iterator迭代器遍歷

Iterator iterator = lists.iterator();
while (iterator.hasNext()){String key = iterator.next().toString();
}

4、三種方式比較

import java.util.ArrayList;
import java.util.Iterator;public class ArrayListFor {private static ArrayList<String> initData(){ArrayList<String> lists = new ArrayList<String>(1000000);for(int i=0; i<1000000; i++){lists.add(i + "abcdefg");}return lists;}private static String forOne(ArrayList<String> lists){StringBuilder sb = new StringBuilder();sb.append("普通For循環(int i=0; i<count; i++)。");sb.append("\r\n");long start = System.currentTimeMillis();for(int i=0; i<lists.size(); i++){String key = lists.get(i);}long end = System.currentTimeMillis();sb.append("duration = [" + (end - start) + "]ms");sb.append("\r\n");return sb.toString();}private static String forTwo(ArrayList<String> lists){StringBuilder sb = new StringBuilder();sb.append("加強For循環(int i : lists)。");sb.append("\r\n");long start = System.currentTimeMillis();for(String str : lists){String key = str;}long end = System.currentTimeMillis();sb.append("duration = [" + (end - start) + "]ms");sb.append("\r\n");return sb.toString();}private static String forThree(ArrayList<String> lists){StringBuilder sb = new StringBuilder();sb.append("Iterator循環(list.iterator())。");sb.append("\r\n");long start = System.currentTimeMillis();Iterator iterator = lists.iterator();while (iterator.hasNext()){String key = iterator.next().toString();}long end = System.currentTimeMillis();sb.append("duration = [" + (end - start) + "]ms");sb.append("\r\n");return sb.toString();}public static String forCycle(ArrayList<String> lists) {StringBuilder sb = new StringBuilder();sb.append("ArrayList遍歷比較:");sb.append("\r\n");sb.append(forOne(lists));sb.append(forTwo(lists));sb.append(forThree(lists));return sb.toString();}public static void main(String[] args) {ArrayList<String> lists = initData();for(int i=0; i<5; i++){System.out.println(forCycle(lists));}}
}

運行結果:

ArrayList遍歷比較:
普通For循環(int i=0; i<count; i++)。
duration = [33]ms
加強For循環(int i : lists)。
duration = [35]ms
Iterator循環(list.iterator())。
duration = [34]msArrayList遍歷比較:
普通For循環(int i=0; i<count; i++)。
duration = [29]ms
加強For循環(int i : lists)。
duration = [32]ms
Iterator循環(list.iterator())。
duration = [32]msArrayList遍歷比較:
普通For循環(int i=0; i<count; i++)。
duration = [26]ms
加強For循環(int i : lists)。
duration = [27]ms
Iterator循環(list.iterator())。
duration = [27]msArrayList遍歷比較:
普通For循環(int i=0; i<count; i++)。
duration = [26]ms
加強For循環(int i : lists)。
duration = [34]ms
Iterator循環(list.iterator())。
duration = [27]msArrayList遍歷比較:
普通For循環(int i=0; i<count; i++)。
duration = [26]ms
加強For循環(int i : lists)。
duration = [27]ms
Iterator循環(list.iterator())。
duration = [28]ms

總結: 普通for循環耗時最少,iterator次之,增強for循環耗時最長。

二、Map遍歷方式

大致分為 增強for循環Iterator迭代器 兩種,而其中每個又各自分為使用 keySet()entrySet() 兩種,所以 一共四種

1、增強for循環 + keySet() 遍歷

for(String key : maps.keySet()){String str = maps.get(key);
}

2、增強for循環 + entrySet() 遍歷

for(Map.Entry<String, String> entry : maps.entrySet()){String str = entry.getValue();
}

3、Iterator + keySet() 遍歷

Iterator iterator = maps.keySet().iterator();
while (iterator.hasNext()){String key = iterator.next().toString();String str = maps.get(key);
}

4、Itorator + entrySet() 遍歷

Iterator iterator = maps.entrySet().iterator();
while (iterator.hasNext()){Map.Entry<String, String> entry = (Map.Entry<String, String>)iterator.next();String str = entry.getValue();
}

5、四種方式比較

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;public class HashMapFor {private static HashMap<String,String> initData(){HashMap<String,String> maps = new HashMap<String, String>(10000000 * 2);for(int i=0; i<10000000; i++){String key = i + "abcdefg";maps.put(key, key);}return maps;}private static String forOne(HashMap<String, String> maps){StringBuilder sb = new StringBuilder();sb.append("增強For循環 + keySet()(int i : map.keySet())。");sb.append("\r\n");long start = System.currentTimeMillis();for(String key : maps.keySet()){String str = maps.get(key);}long end = System.currentTimeMillis();sb.append("duration = [" + (end - start) + "]ms");sb.append("\r\n");return sb.toString();}private static String forTwo(HashMap<String, String> maps){StringBuilder sb = new StringBuilder();sb.append("增強For循環 + entrySet()(Entry<> entry : map.entrySet())。");sb.append("\r\n");long start = System.currentTimeMillis();for(Map.Entry<String, String> entry : maps.entrySet()){String str = entry.getValue();}long end = System.currentTimeMillis();sb.append("duration = [" + (end - start) + "]ms");sb.append("\r\n");return sb.toString();}private static String forThree(HashMap<String, String> maps){StringBuilder sb = new StringBuilder();sb.append("Iterator循環 + keySet()(map.keySet().iterator())。");sb.append("\r\n");long start = System.currentTimeMillis();Iterator iterator = maps.keySet().iterator();while (iterator.hasNext()){String key = iterator.next().toString();String str = maps.get(key);}long end = System.currentTimeMillis();sb.append("duration = [" + (end - start) + "]ms");sb.append("\r\n");return sb.toString();}private static String forFour(HashMap<String, String> maps){StringBuilder sb = new StringBuilder();sb.append("Iterator循環 + entrySet()(map.entrySet().iterator())。");sb.append("\r\n");long start = System.currentTimeMillis();Iterator iterator = maps.entrySet().iterator();while (iterator.hasNext()){Map.Entry<String, String> entry = (Map.Entry<String, String>)iterator.next();String str = entry.getValue();}long end = System.currentTimeMillis();sb.append("duration = [" + (end - start) + "]ms");sb.append("\r\n");return sb.toString();}public static String forCycle(HashMap<String, String> maps) {StringBuilder sb = new StringBuilder();sb.append("HashMap遍歷比較:");sb.append("\r\n");sb.append(forOne(maps));sb.append(forTwo(maps));sb.append(forThree(maps));sb.append(forFour(maps));return sb.toString();}public static void main(String[] args) {HashMap<String, String> maps = initData();for(int i=0; i<5; i++){System.out.println(forCycle(maps));}}
}

運行結果:

HashMap遍歷比較:
增強For循環 + keySet()int i : map.keySet())。
duration = [66]ms
增強For循環 + entrySet()Entry<> entry : map.entrySet())。
duration = [46]ms
Iterator循環 + keySet()(map.keySet().iterator())。
duration = [68]ms
Iterator循環 + entrySet()(map.entrySet().iterator())。
duration = [45]msHashMap遍歷比較:
增強For循環 + keySet()int i : map.keySet())。
duration = [63]ms
增強For循環 + entrySet()Entry<> entry : map.entrySet())。
duration = [44]ms
Iterator循環 + keySet()(map.keySet().iterator())。
duration = [65]ms
Iterator循環 + entrySet()(map.entrySet().iterator())。
duration = [47]msHashMap遍歷比較:
增強For循環 + keySet()int i : map.keySet())。
duration = [48]ms
增強For循環 + entrySet()Entry<> entry : map.entrySet())。
duration = [37]ms
Iterator循環 + keySet()(map.keySet().iterator())。
duration = [72]ms
Iterator循環 + entrySet()(map.entrySet().iterator())。
duration = [34]msHashMap遍歷比較:
增強For循環 + keySet()int i : map.keySet())。
duration = [54]ms
增強For循環 + entrySet()Entry<> entry : map.entrySet())。
duration = [41]ms
Iterator循環 + keySet()(map.keySet().iterator())。
duration = [49]ms
Iterator循環 + entrySet()(map.entrySet().iterator())。
duration = [34]msHashMap遍歷比較:
增強For循環 + keySet()int i : map.keySet())。
duration = [47]ms
增強For循環 + entrySet()Entry<> entry : map.entrySet())。
duration = [31]ms
Iterator循環 + keySet()(map.keySet().iterator())。
duration = [47]ms
Iterator循環 + entrySet()(map.entrySet().iterator())。
duration = [31]ms

總結:

  • entrySet()keySet() 效率要好點
  • Iterator 要比 for each 效率要好點
  • 所以:Iterator + entrySet() 效率最好(參考需謹慎)

三、java開發手冊(關于map的)

  • 推薦使用 entrySet 遍歷 Map 集合 KV,而不是使用 keySet 方式遍歷

  • 原因:keySet 其實是遍歷了2次,一次是轉為 Iterator 對象,另一次是從 hashMap 中取出 key 所對應的 value。而 entrySet 只是遍歷了一次就把 keyvalue 都放到了 entry 中,效率更高。如果是JDK8,使用 Map.foreach 方法。

  • 正例:values() 返回的是V值集合,是一個 list 集合對象,keySet() 返回的是 K值集合,是一個Set集合對象,entrySet() 返回的是 K-V值組合集合。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/446738.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/446738.shtml
英文地址,請注明出處:http://en.pswp.cn/news/446738.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

C++primer 12章 動態內存和智能指針

C引入智能指針的目的 使用智能指針來管理動態分配的對象&#xff0c;當一個對象應該被釋放的時候&#xff0c;指向他的智能指針確保自動釋放它 內存分配 靜態內存&#xff1a;局部static對象、類static數據成員、定義在任何函數之外的變量棧內存&#xff1a;定義在函數內的非…

Mac下iTerm2的安裝與配置

目錄一、iTerm2簡介二、下載以及安裝三、iTerm2主題配置四、配置Oh My Zsh1、安裝方式&#xff08;1&#xff09;一鍵安裝&#xff08;2&#xff09;手動安裝3、切換zsh4、修改主題五、配置Meslo字體六、聲明高亮七、自動建議填充八、iTerm2快速隱藏和顯示九、iTerm2隱藏用戶名…

codeforces 282A-C語言解題報告

282A題目網址 題目解析 1.第一行輸入n(表示有n條語句都要執行),再輸入X,X(都表示X1),–X,X–(都表示X-1),最初X0,輸出X的值 2.使用字符數組去存放每一行的字符串,因為字符串,所以直接整體存入scanf("%s",c); 3.因為字符數組最后一個是’\0’去表示末尾,所以要開辟…

Java命令:jinfo — 查看進程參數

目錄一、簡介二、常用命令1、jinfo -flags pid : 打印當前指定java進程中已經設定的所有JVM參數信息2、jinfo -flag pid : 打印指定名稱的參數3、jinfo -flag [|-] pid : 打開或關閉參數4、jinfo -sysprops pid : 打印當前java進程中設定的系統環境參數一、簡介 jinfo 是 JDK …

C++primer第八章 IO庫 8.1 IO類

IO庫設施 istream &#xff08;輸入流&#xff09;類型&#xff0c;提供輸入操作。ostream &#xff08;輸出流&#xff09;類型&#xff0c;提供輸出操作。cin,—個 istream對象&#xff0c;從標準輸入讀取數據。cout, 一個ostream對象&#xff0c;向標準輸出寫入數據。cerr…

2014年英語一作文partB漫畫作文

題目 Write an essay of 160-200 words based on the following drawing.In your essay you should describe the drawing brieflyexplain its intended meaning,give your comments 做題點 1.使用三段式,第一段:圖片內容;第二段:圖片暗示;第三段:寫自己的評論 2.描述圖片…

Spring Cloud 系列之 Nacos 配置中心

目錄一、Nacos簡介二、Nacos安裝及配置1、環境準備2、安裝包下載&#xff08;1&#xff09;源碼方式&#xff08;2&#xff09;發行包方式3、啟動Nacos服務4、Nacos數據庫配置&#xff08;1&#xff09;MySQL數據源&#xff08;2&#xff09;初始化 MySQL 數據庫&#xff08;3&…

C++primer第八章 IO庫 8.2 文件輸入輸出

8.2文件輸入輸出 頭文件fstream定義了三個類型來支持文件IO&#xff1a;ifstream從一個給定文件讀取數據&#xff0c;ofstream向一個給定文件寫入數據&#xff0c;以及fstream可以讀寫給定文件。在17.5.3節中&#xff08;第676頁&#xff09;我們將介紹如何對同一個文件流既讀…

codeforces 112A-C語言解題報告

112A題目網址 題目解析 1.輸入兩行字符串,不區分大小寫地使用字典序去比較大小 A<B -1 A>B 1 AB 0 舉例: 輸入 abcdefg AbCdEfF 輸出 1 2.字典序:在遇到第一個不同的字符時,比較的大小,就是字符串的大小 列舉法: 1.列出所有情況 1)a[i]是大寫,b[i]是小寫 a[i]轉換為小…

SpringBoot 集成 Nacos

目錄一、前言二、Nacos集成1、引入Nacos依賴2、設置Nacos配置3、加載Nacos配置中心配置項4、Nacos集成驗證5、Nacos配置中心配置項動態生效Nacos安裝詳見&#xff1a;Spring Cloud 系列之 Nacos 配置中心 一、前言 上一篇已經講解了怎樣安裝安裝、啟動、配置 Nacos&#xff0c…

C++primer第八章 IO庫 8.3string流

8.3string流 sstream頭文件定義了三個類型來支持內存IO,這些類型可以向string寫入數據,從string讀取數據&#xff0c;就像string是一個IO流一樣。istringstream從string讀取數據&#xff0c;ostringstream向string寫入數據&#xff0c;而頭文件stringstream既可從string讀數據…

英語口語海報演講--東軟

海報 海報上的內容 Nuclear waste water 1.Damage the devastating impact of nuclear radiation on the world 2.Marine life genetically mutated or dead 3.water resources polluted water resources 4.the future of humanity genetic damage/food and environment destr…

Java中 List、Set、Map遍歷方式以及性能比較

目錄一、簡介二、遍歷方式1、ArrayList遍歷方式&#xff08;1&#xff09;for循環遍歷&#xff08;2&#xff09;foreach循環遍歷&#xff08;3&#xff09;Iterator迭代器遍歷2、LinkedList遍歷方式&#xff08;1&#xff09;for循環遍歷&#xff08;2&#xff09;foreach循環…

codeforces 263A-C語言解題報告

263A題目網址 題目解析 1.輸入5*5的矩陣(下標從到5),包含24個0和一個1,問如何移動最小的次數(i相鄰行或列)可以讓1位于3行3列 舉例: 輸入: 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 輸出: 3 注意點 1.因為數組是從0開始的,所以減2就行 row-2col-2 2.使用整型二維…

一個DEMO讓你徹底理解線程池

目錄一、簡介二、線程池任務場景場景一&#xff1a;提交5個任務&#xff0c;執行總耗時500ms場景二&#xff1a;提交10個任務&#xff0c;執行總耗時500ms場景三&#xff1a;提交11個任務&#xff0c;執行總耗時1000ms場景四&#xff1a;提交20個任務&#xff0c;執行總耗時100…

C++primer第九章 順序容器 9.1 順序容器概述 9.2容器庫概覽

一個容器就是一些特定類型對象的集合。順序容器(sequentialcontainer)為程序員提供了控制元素存儲和訪問順序的能力。這種順序不依賴于元素的值&#xff0c;而是與元素加入容器時的位置相對應。與之相對的&#xff0c;我們將在第11章介紹的有序和無序關聯容器&#xff0c;則根據…

SpringBoot 啟動報錯:Failed to configure a DataSource: ‘url‘ attribute is not specified and no emb

目錄一、報錯日志二、原因分析三、問題排查四、解決方案方案一&#xff1a;如果項目不需要數據庫相關信息就排除此類的autoconfig方案二&#xff1a;配置文件添加數據庫鏈接信息方案三&#xff1a;配置pom.xml中yml或者properties掃描一、報錯日志 **************************…

codeforces 339A-C語言解題報告

339A題目網址 題目解析 1.輸入如321的式子,升序排序(從小到大)成123 舉例: 輸入: 11313 輸出: 11133 2.對字符串進行排序采取拍冒泡排序算法 char c0; for(i0;i<strlen(s)-1;i) {for(j0;j<strlen(s)-1;j){if(s[j]>s[j1]){cs[j];s[j]s[j1];s[j1]c;}} }代碼 #includ…

C++primer第九章 順序容器 9.3 順序容器操作

9.3順序容器操作 順序容器和關聯容器的不同之處在于兩者組織元素的方式。這些不同之處直接關系到了元素如何存儲、訪問、添加以及刪除。上一節介紹了所有容器都支持的操作&#xff08;羅列于表9.2&#xff08;第295頁&#xff09;&#xff09;。本章剩余部分將介紹順序容器所特…

SpringBoot 集成Nacos報錯(一)

目錄配置信息報錯信息解決方案配置信息 <project><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.2</version><relativePath/></parent>…