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

目錄

  • 一、簡介
  • 二、遍歷方式
    • 1、ArrayList遍歷方式
      • (1)for循環遍歷
      • (2)foreach循環遍歷
      • (3)Iterator迭代器遍歷
    • 2、LinkedList遍歷方式
      • (1)for循環遍歷
      • (2)foreach循環遍歷
      • (3)Iterator迭代器遍歷
    • 3、HashSet遍歷方式
      • (1)foreach循環遍歷
      • (2)Iterator迭代器遍歷
    • 4、HashMap遍歷方式
      • (1)entrySet遍歷
      • (2)Iterator迭代器遍歷
    • 5、LinkedHashMap遍歷方式
      • (1)entrySet遍歷
      • (2)Iterator迭代器遍歷
  • 三、性能比較


一、簡介

ListSet 都繼承 Collection 接口,Map 不是。

  • List:元素有序存儲,元素可重復,取出來的順序可能和放入的順序不同,支持for循環和迭代器遍歷;

  • Set:元素無序存儲,且唯一,不能包含重復的元素,不支持for循環遍歷,支持迭代器遍歷;

  • Map:元素無序存儲,key值唯一不能重復,value值可重復,支持迭代器遍歷;

List、Set、Map實現類

  • ListArrayListLinkedListVector

  • SetHashSetTreeSetLinkedHashSet

  • MapHashMapTreeMapHashTableLinkedHashMap

線程安全 / 線程不安全

  • 線程安全:Vector、HashTable

  • 線程不安全:ArrayList、LinkedList、HashSet、LinkedHashSet、HashMap、TreeMap、LinkedHashMap

下面我們只拿出 ArrayListLinkedListHashSetHashMapLinkedHashMap 來講解遍歷方式以及遍歷性能比較。



二、遍歷方式

1、ArrayList遍歷方式

ArrayList有三種遍歷方式:for循環遍歷foreach循環遍歷Iterator迭代器遍歷


(1)for循環遍歷

ArrayList<String> lists = new ArrayList<String>();
for(int i=0;i<lists.size();i++){String line = lists.get(i);
}

(2)foreach循環遍歷

ArrayList<String> lists = new ArrayList<String>();
for(String str : lists){String line = str;
}

(3)Iterator迭代器遍歷

ArrayList<String> lists = new ArrayList<String>();
Iterator<String> iterator = lists.iterator();
while (iterator.hasNext()){String line = iterator.next();
}

2、LinkedList遍歷方式

LinkedList有三種遍歷方式:for循環遍歷foreach循環遍歷Iterator迭代器遍歷


(1)for循環遍歷

LinkedList<String> lists = new LinkedList<String>();
for(int i=0;i<lists.size();i++){String line = lists.get(i);
}

(2)foreach循環遍歷

LinkedList<String> lists = new LinkedList<String>();
for(String str : lists){String line = str;
}

(3)Iterator迭代器遍歷

LinkedList<String> lists = new LinkedList<String>();
Iterator<String> iterator = lists.iterator();
while (iterator.hasNext()){String line = iterator.next();
}

3、HashSet遍歷方式

HashSet有兩種遍歷方式:foreach循環遍歷Iterator迭代器遍歷


(1)foreach循環遍歷

HashSet<String> hashSets = new HashSet<String>();
for(String str : hashSets){String line = str;
}

(2)Iterator迭代器遍歷

HashSet<String> hashSets = new HashSet<String>();
Iterator<String> iterator = hashSets.iterator();
while (iterator.hasNext()){String line = iterator.next();
}

4、HashMap遍歷方式

HashMap有三種遍歷方式:keySet循環遍歷entrySet遍歷Iterator迭代器遍歷

下面我們只講解 entrySet遍歷Iterator迭代器遍歷


(1)entrySet遍歷

HashMap<String, String> hashMaps = new HashMap<String, String>();
for(Map.Entry<String, String> entry : hashMaps.entrySet()){String line = entry.getKey();
}

(2)Iterator迭代器遍歷

HashMap<String, String> hashMaps = new HashMap<String, String>();
Iterator iterator = hashMaps.entrySet().iterator();
while (iterator.hasNext()){Map.Entry<String, String> entry = (Map.Entry<String, String>)iterator.next();String line = entry.getKey();
}

5、LinkedHashMap遍歷方式

LinkedHashMap有三種遍歷方式:keySet循環遍歷entrySet遍歷Iterator迭代器遍歷

下面我們只講解 entrySet遍歷Iterator迭代器遍歷


(1)entrySet遍歷

LinkedHashMap<String, String> linkedHashMaps = new LinkedHashMap<String, String>();
for(Map.Entry<String, String> entry : linkedHashMaps.entrySet()){String line = entry.getKey();
}

(2)Iterator迭代器遍歷

LinkedHashMap<String, String> linkedHashMaps = new LinkedHashMap<String, String>();
Iterator iterator = linkedHashMaps.entrySet().iterator();
while (iterator.hasNext()){Map.Entry<String, String> entry = (Map.Entry<String, String>)iterator.next();String line = entry.getKey();
}

三、性能比較

不同數量級的性能差異是比較大的,下面我們分別在30、100、1000、10000、100000數量級進行性能比較。

完整代碼如下:

package com.example.springbootdemo.util;import java.util.*;public class Test {public static void main(String[] args) {compare();}private static ArrayList<String> lists = new ArrayList<String>();private static LinkedList<String> linkedLists = new LinkedList<String>();private static HashSet<String> hashSets = new HashSet<String>();private static HashMap<String, String> hashMaps = new HashMap<String, String>();private static LinkedHashMap<String, String> linkedHashMaps = new LinkedHashMap<String, String>();private static void compare(){compareInit(100000);compare1();}private static void compareInit(int count){lists.clear();linkedLists.clear();hashMaps.clear();hashSets.clear();linkedHashMaps.clear();String str = "abcdefg_";String one = "";for(int i=0;i<count;i++){one = str + i;lists.add(one);linkedLists.add(one);hashSets.add(one);hashMaps.put(one, one);linkedHashMaps.put(one, one);}}private static final String listFor               = "ArrayList for          duration";private static final String listForeach           = "ArrayList foreach      duration";private static final String listIterator          = "ArrayList Iterator     duration";private static final String linkedListFor         = "LinkedList for         duration";private static final String linkedListForeach     = "LinkedList foreach     duration";private static final String linkedListIterator    = "LinkedList Iterator    duration";private static final String hashSetForeach        = "HashSet foreach        duration";private static final String hashSetIterator       = "HashSet Iterator       duration";private static final String hashMapEntry          = "HashMap entry          duration";private static final String hashMapIterator       = "HashMap Iterator       duration";private static final String linkedHashMapEntry    = "LinkedHashMap entry    duration";private static final String linkedHashMapIterator = "LinkedHashMap Iterator duration";private static void compare1(){for(int i=0;i<5;i++){System.out.println("------------------------------");listOne();listTwo();listThree();linkedListOne();linkedListTwo();linkedListThree();hashSetOne();hashSetTwo();hashMapOne();hashMapTwo();linkedHashMapOne();linkedHashMapTwo();System.out.println();}}private static void listOne(){String line = "";long start = System.nanoTime();for(int i=0;i<lists.size();i++){line = lists.get(i);}long end = System.nanoTime();print(start, end, listFor);}private static void listTwo(){String line = "";long start = System.nanoTime();for(String str : lists){line = str;}long end = System.nanoTime();print(start, end, listForeach);}private static void listThree(){String line = "";long start = System.nanoTime();Iterator<String> iterator = lists.iterator();while (iterator.hasNext()){line = iterator.next();}long end = System.nanoTime();print(start, end, listIterator);}private static void linkedListOne(){String line = "";long start = System.nanoTime();for(int i=0;i<linkedLists.size();i++){line = linkedLists.get(i);}long end = System.nanoTime();print(start, end, linkedListFor);}private static void linkedListTwo(){String line = "";long start = System.nanoTime();for(String str : linkedLists){line = str;}long end = System.nanoTime();print(start, end, linkedListForeach);}private static void linkedListThree(){String line = "";long start = System.nanoTime();Iterator<String> iterator = linkedLists.iterator();while (iterator.hasNext()){line = iterator.next();}long end = System.nanoTime();print(start, end, linkedListIterator);}private static void hashSetOne(){String line = "";long start = System.nanoTime();for(String str : hashSets){line = str;}long end = System.nanoTime();print(start, end, hashSetForeach);}private static void hashSetTwo(){String line = "";long start = System.nanoTime();Iterator<String> iterator = hashSets.iterator();while (iterator.hasNext()){line = iterator.next();}long end = System.nanoTime();print(start, end, hashSetIterator);}private static void hashMapOne(){String line = "";long start = System.nanoTime();for(Map.Entry<String, String> entry : hashMaps.entrySet()){line = entry.getKey();}long end = System.nanoTime();print(start, end, hashMapEntry);}private static void hashMapTwo(){String line = "";long start = System.nanoTime();Iterator iterator = hashMaps.entrySet().iterator();while (iterator.hasNext()){Map.Entry<String, String> entry = (Map.Entry<String, String>)iterator.next();line = entry.getKey();}long end = System.nanoTime();print(start, end, hashMapIterator);}private static void linkedHashMapOne(){String line = "";long start = System.nanoTime();for(Map.Entry<String, String> entry : linkedHashMaps.entrySet()){line = entry.getKey();}long end = System.nanoTime();print(start, end, linkedHashMapEntry);}private static void linkedHashMapTwo(){String line = "";long start = System.nanoTime();Iterator iterator = linkedHashMaps.entrySet().iterator();while (iterator.hasNext()){Map.Entry<String, String> entry = (Map.Entry<String, String>)iterator.next();line = entry.getKey();}long end = System.nanoTime();print(start, end, linkedHashMapIterator);}private static void print(long start, long end, String tip){System.out.println(tip + " = [" + ((double)((end - start)/1000))/1000 + "]ms");}
}

我們經過多輪測試,取相對合理的結果進行展示,單位為:毫秒(ms)

type30100100010000100000
ArrayList - for0.0030.0080.0570.5190.674
ArrayList - foreach0.0120.0090.0650.4950.632
ArrayList - Iterator0.0100.0070.0740.4990.62
LinkedList - for0.0310.0390.49864.04416374.155
LinkedList - foreach0.0110.0120.0750.5261.989
LinkedList - Iterator0.0080.0080.0680.5181.98
HashSet - foreach0.0090.0250.0870.7541.955
HashSet - Iterator0.0050.0110.0930.731.931
HashMap - entrySet0.0120.0250.0920.9552.007
HashMap - Iterator0.0090.0150.0820.9052.0
LinkedHashMap - entrySet0.0160.0250.090.7192.596
LinkedHashMap - Iterator0.0120.0130.0780.7042.46

單個類型不同遍歷方式性能比較總結:

  • ArrayList:三種遍歷方式性能差距不大,數量級較小時,for循環遍歷更優,數量級較大時,Iterator迭代器遍歷方式性能更優;

  • LinkedList:三種遍歷方式中for循環遍歷性能最差,其他兩種方式性能差距比較小,但是Iterator迭代器遍歷方式性能更優;

  • HashSet:兩種遍歷方式性能差距不大,但是Iterator迭代器遍歷方式性能更優;

  • HashMap:兩種遍歷方式性能差距不大,但是Iterator迭代器遍歷方式性能更優;

  • LinkedHashMap:兩種遍歷方式性能差距不大,但是Iterator迭代器遍歷方式性能更優;


整體性能比較總結:

  • 同等數量級,ArrayList的遍歷性能更優;

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

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

相關文章

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>…

C++primer第九章 順序容器 9.4 vector對象是如何增長的

為了支持快速隨機訪問&#xff0c;vector將元素連續存儲&#xff0c;每個元素緊挨著前一個元素存儲。通常情況下&#xff0c;我們不必關心一個標準庫類型是如何實現的&#xff0c;而只需關心它如何使用。然而&#xff0c;對于vector和string,其部分實現滲透到了接口中。假定容器…

codeforces 281A-C語言解題報告

281A題目網址 題目解析 1.字符串首字母大寫 代碼 #include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int main() {char s[1000]{\0};scanf("%s",s);if(s[0]>A&&s[0]<Z){printf("%s",s…

SpringBoot 配置文件bootstrap和application的區別

目錄一、SpringBoot配置文件二、bootstrap和application區別三、bootstrap和application的應用場景一、SpringBoot配置文件 bootstrap&#xff08;.yml 或者 .properties&#xff09; application&#xff08;.yml 或者 .properties&#xff09; 二、bootstrap和application區…

C++primer第九章 順序容器 9.5 額外的string操作

除了順序容器共同的操作之外&#xff0c;string類型還提供了一些額外的操作。這些操作中 的大部分要么是提供string類和C 風格字符數組之間的相互轉換,要么是增加了允許我們用下標代替迭代器的版本。標準庫string類型定義了大量函數。幸運的是&#xff0c;這些函數使用了重復的…

Zookeeper Mac下安裝操作

目錄一、下載Zookeeper二、修改配置1、設置啟動配置文件2、修改配置三、啟動Zookeeper服務命令1、bin目錄下執行&#xff08;1&#xff09;啟動Zookeeper命令&#xff08;2&#xff09;查看Zookeeper狀態命令&#xff08;3&#xff09;停止Zookeeper命令2、配置環境變量執行&am…

codeforces 266A-C語言解題報告

266A題目網址 題目解析 1.輸入n(1–50)個石頭個數,輸入RGB的石頭顏色,求問拿走最小的石頭個數,讓它們相鄰的石頭顏色不同 代碼 #include<stdio.h> #include<stdlib.h> #include<string.h> int main() {int n,i,count0;char s[50]{\0};scanf("%d&quo…

2014年考研英語二作文PartB圖表題

作文詳細解析 題目 Write an essay based on the following chart, in which you should interpret the chart, and give your comments You should write about 150 words on the ANSWER SHEET.(15 points) 注意點 1.圖表題在第一段描述圖表信息時,一定要寫清楚y軸變化…

Zookeeper 終端命令

目錄一、服務端命令1、啟動Zookeeper服務命令2、查看Zookeeper狀態命令3、停止Zookeeper服務命令4、啟動Zookeeper客戶端命令二、客戶端命令1、查看幫助2、查看當前znode所包含的內容3、創建znode4、創建短暫znode5、創建帶序號znode6、創建短暫帶序號znode7、獲取znode數據8、…

C++primer第九章 順序容器 9.6 容器適配器

9.6容器適配器 除了順序容器外&#xff0c;標準庫還定義了三個順序容器適配器&#xff1a;stack、queue和priority_queue適配器(adaptor)是標準庫中的一個通用概念。容器、迭代器和函數<369I都有適配器。本質上&#xff0c;一個適配器是一種機制&#xff0c;能使某種事物的…

codeforces 236A-C語言解題報告

236題目網址 題目解析 1.輸入字符串,判斷其中不同的字符個數,奇偶輸出不同的語句 2.使用冒泡排序去排序,當遇到s[k]!s[k1]時進行計數 代碼 #include<stdio.h> #include<stdlib.h> #include<string.h> int main() {char s [100]{\0};int i,j,k,count0;cha…

SpringBoot Controller接收參數的常用方式

文章目錄一、請求路徑參數1、PathVariable二、Body參數1、RequestParam2、RequestBody三、請求頭參數和Cookie參數1、RequestHeader2、CookieValue一、請求路徑參數 1、PathVariable 注解為&#xff1a; org.springframework.web.bind.annotation.PathVariable獲取路徑參數&…

C++primer第十章 泛型算法 10.1 概述 10.2 初識泛型算法

大多數算法都定義在頭文件algorithm中。標準庫還在頭文件numeric中定義了 一組數值泛型算法一般情況下&#xff0c;這些算法并不直接操作容器&#xff0c;而是遍歷由兩個迭代器指定的一個元素范圍(參見9.2.1節&#xff0c;第296頁)來進行操作。通常情況下&#xff0c;算法遍歷范…

MySQL Mac安裝教程

文章目錄一、下載安裝包二、安裝三、啟動MySQL四、環境變量設置一、下載安裝包 下載地址&#xff1a;https://downloads.mysql.com/archives/community/ 二、安裝 雙擊安裝包&#xff0c;然后一直點繼續即可。 三、啟動MySQL 打開 系統偏好設置&#xff0c;會發現多了一個…