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.mzph.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;会发现多了一个…