【QA】Java集合的常见遍历方式

embedded/2024/10/21 23:02:28/

前言

本文主要讲述Java集合常见的遍历方式。

通用遍历方式 | Collection集合

迭代器Iterator遍历

java">Collection<Student> c = new ArrayList<>();c.add(new Student("张三", 23));
c.add(new Student("李四", 24));
c.add(new Student("王五", 25));// 1. 获取迭代器
Iterator<Student> it = c.iterator();// 2. 循环判断, 集合中是否还有元素
while (it.hasNext()) {// 3. 调用next方法, 将元素取出Student stu = it.next();System.out.println(stu.getName() + "---" + stu.getAge());
}

增强for循环:本质还是迭代器

java">Collection<Student> c = new ArrayList<>();c.add(new Student("张三", 23));
c.add(new Student("李四", 24));
c.add(new Student("王五", 25));// 使用增强for循环遍历集合:内部还是迭代器,通过.class文件可以看出来
for (Student stu : c) {System.out.println(stu);
}

forEach方法:本质是匿名内部类

java">Collection<Student> c = new ArrayList<>();c.add(new Student("张三", 23));
c.add(new Student("李四", 24));
c.add(new Student("王五", 25));// foreach方法遍历集合:匿名内部类
c.forEach(stu -> System.out.println(stu));

额外的遍历方式 | List集合

普通for循环

java">List<String> list = new ArrayList<>();
list.add("abc");
list.add("bbb");
list.add("ccc");
list.add("abc");// 普通for循环
for (int i = 0; i < list.size(); i++) {String s = list.get(i);System.out.println(s);
}

ListIterator【List集合特有】

java">List<String> list = new ArrayList<>();
list.add("abc");
list.add("bbb");
list.add("ccc");
list.add("abc");ListIterator<String> it = list.listIterator();while (it.hasNext()) {String s = it.next();System.out.println(s);
}

【补充】ListIterator和Iterator的区别

两者的区别主要体现在遍历过程中添加、删除元素上。具体见下表:(表中的方法均在遍历过程中使用)

add()remove()
不管在任何迭代过程中,调用集合本身的方法引发异常引发异常
Iterator迭代过程中,调用Iterator迭代器的方法不支持支持
ListIterator迭代过程中,调用ListIterator迭代器的方法支持支持

针对ListIterator迭代器:

  • 删除操作:删除当前迭代到的数据
  • 添加操作:添加数据到当前迭代到的数据后面
  • 在一个迭代内,不允许既增加,又删除
java">package com.itheima.collection.list;import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;public class ListDemo3 {public static void main(String[] args) {List<String> list = new ArrayList<>();list.add("眼瞅着你不是真正的高兴");list.add("温油");list.add("离开俺们这旮表面");list.add("伤心的人别扭秧歌");list.add("私奔到东北");ListIterator<String> it = list.listIterator();while (it.hasNext()) {String s = it.next();if ("温油".equals(s)) {it.add("哈哈");  		// 迭代器的添加操作:没问题it.remove();		 // 迭代器的删除操作:没问题(但是和上边的添加操作放在一个迭代内,就报错了)list.add("哈哈"); 	// 集合本身的添加操作:报错list.remove("温油"); 	// 集合本身的删除操作:报错}}System.out.println(list);}
}

额外的遍历方式 | Map集合

增强For循环(迭代器)

增强for循环,本质是迭代器的方式遍历

  • map.keySet() + map.get(key):获取map集合的所有键,并用增强for遍历所有键,然后用get方法获取每一个键对应的值
  • map.values():获取map集合的所有值,进行遍历
  • map.entrySet() + entry.getKey() + entry.getValue():获取map集合的Entry对象,每个对象里面包含键和值

通过forEach方法遍历

  • map.forEach:直接获取每一个集合对象的键和值,进行遍历操作

示例

java">import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;public class MapTest {public static void main(String[] args) {HashMap<Integer, String> testMap = new HashMap<>();testMap.put(1, "One");testMap.put(2, "Two");testMap.put(3, "Three");testMap.put(4, "Four");testMap.put(5, "Five");// 增强for:第一种for (Integer key : testMap.keySet()) {System.out.print(key + "-" + testMap.get(key) + "\t");}System.out.println("\nforeach keySet");// 增强for:第二种for (String value : testMap.values()) {System.out.print(value + "\t");}System.out.println("\nforeach values");// 增强for:第三种for (Map.Entry<Integer, String> entry : testMap.entrySet()) {System.out.print(entry.getKey() + "-" + entry.getValue() + "\t");}System.out.println("\nforeach entrySet");// 增强for:第三种(迭代器形式,上述第三种本质也是迭代器方式,但是书写更简单)Iterator<Map.Entry<Integer, String>> it = testMap.entrySet().iterator();while (it.hasNext()) {Map.Entry<Integer, String> entry = it.next();System.out.print(entry.getKey() + "-" + entry.getValue() + "\t");}System.out.println("\nentrySet iterator");// foreach:Map的forEach方法,Java8独有testMap.forEach((key, value) -> {System.out.print(key + "-" + value + "\t");});System.out.println("\nMap.forEach()");}
}
运行结果:
1-One 2-Two 3-Three 4-Four 5-Five
foreach keySet
One Two Three Four Five
foreach values
1-One 2-Two 3-Three 4-Four 5-Five
foreach entrySet
1-One 2-Two 3-Three 4-Four 5-Five
entrySet iterator
1-One 2-Two 3-Three 4-Four 5-Five
Map.forEach()

http://www.ppmy.cn/embedded/30636.html

相关文章

【Java笔记】CAS比较的是什么+交换的是什么+自旋到啥时候

文章目录 什么是CASCAS原理CAS的原子性CAS的三个问题问题一&#xff1a;ABA解决方法 问题二&#xff1a;CPU开销过大解决方法 问题三&#xff1a;不能保证代码块的原子性解决方法 Reference 之前看CAS一致迷迷糊糊的&#xff0c;知道它通过自旋来避免多线程冲突&#xff0c;然后…

MATLAB 微积分

MATLAB 微积分 MATLAB提供了多种方法来解决微分和积分问题&#xff0c;求解任意程度的微分方程式以及计算极限。最重要的是&#xff0c;您可以轻松求解复杂函数的图&#xff0c;并通过求解原始函数及其导数来检查图上的最大值&#xff0c;最小值和其他文具点。 本章将讨论微…

前端工程化05-初始前端工程化Node基本介绍安装配置基础知识

6、初始前端工程化 6.1、工程化概述 虽然前几篇我的目录标题写的前端工程化&#xff0c;但是那些东西并不属于前端工程化的内容&#xff0c;更倾向于是js、jq当中的东西&#xff0c;下面我们将接触真正的前端工程化。 前端工程化开发其实现在是离不开一个东西的&#xff0c;…

rust将json字符串直接转为map对象或者hashmap对象

有些时候我们还真的不清楚返回的json数据里面到底有哪些数据&#xff0c;数据类型是什么等&#xff0c;这个时候就可以使用批处理的方式将json字符串转为一个对象&#xff0c;然后通过这个对象的get方法来获取json里面的数据。 pub async fn test_json(&self) {let json_st…

QT-构造函数

类的构造函数是类的一种特殊的成员函数&#xff0c;它会在每次创建类的新对象时执行。 构造成员变量的初始化值&#xff0c;内存空间等 构造函数的名称与类的名称是完全相同的&#xff0c;并且不会返回任何类型&#xff0c;也不会返回 void。构造函数可用于为某些成员变量设置…

React Context

Context https://juejin.cn/post/7244838033454727227?searchId202404012120436CD549D66BBD6C542177 context 提供了一个无需为每层组件手动添加 props, 就能在组件树间进行数据传递的方法 React 中数据通过 props 属性自上而下(由父及子)进行传递&#xff0c;但此种用法对…

如何搭建本地的 NPM 私有仓库 Nexus

NPM 本地私有仓库&#xff0c;是在本地搭建NPM私有仓库&#xff0c;对公司级别的组件库进行管理。在日常开发中&#xff0c;经常会遇到抽象公共组件的场景&#xff0c;在项目内部进行公用。新的项目开始时&#xff0c;也会拷贝一份创建一个新的项目&#xff0c;这样做不易于管理…

Redis---------实现短信登录业务

目录 基于Session的短信登录 ①首先看他的业务逻辑 ②进行代码逻辑处理 基于Redis的短信登录 ①首先看他的业务逻辑 ②进行代码逻辑处理 Controller&#xff1a; Service接口&#xff1a; Service实例&#xff1a; Mapper&#xff1a; 封装ThreadLocal线程的数据操作&#x…