Java中foreach用法及常用集合操作

李宏毅机器学习hw3 Homework 3 - Convolutional Neural Network 1作业概述 在food_11文件中有三个文件分别是training、validation、testing,打开training和validation可以看见总共有11种食物(0-10的类别编号),而testing是没有类别编号的。 然后用卷积神经网络对食物图片进行分类。 2导入用到的库 torch库 这个我弄了半天,直接pip总是timeout,用镜像源下下来又出现OSError: [WinError.. 阅读详情

foreach语句是java5的新特征之一,在遍历数组、集合方面,foreach为开发人员提供了极大的方便。 
foreach语句是for语句的特殊简化版本,但是foreach语句并不能完全取代for语句,然而,任何的foreach语句都可以改写为for语句版本。 
foreach并不是一个关键字,习惯上将这种特殊的for语句格式称之为“foreach”语句。从英文字面意思理解foreach也就是“for 每一个”的意思。实际上也就是这个意思。 foreach的语句格式:for(元素类型t 元素变量x : 遍历对象obj){     引用了x的java语句;} 下面通过几个例子简单例子看看foreach是如何简化编程的。

1.首先增强for循环和iterator遍历的效果是一样的,也就说增强for循环的内部也就是调用iteratoer实现的,

但是增强for循环有些缺点,例如不能在增强循环里动态的删除集合内容。不能获取下标等。
2.ArrayList由于使用数组实现,因此下标明确,最好使用普通循环。
3.而对于LinkedList 由于获取一个元素,要从头开始向后找,因此建议使用增强for循环,也就是iterator。

我这里用的是Junit的进行的测试。


package com.test;

import java.util.ArrayList;

/**
 * 增强for循环
 * 
 */
public class EnhanceDemo {
	/**
	 * 操作数组
	 */
	@Test
	public void testEnhance1() {
		int[] i = { 1, 2, 3, 4 };
		for (int num : i) {
			System.out.println("testEnhance1--> num: " + num);
		}
	}

	/**
	 * 操作List集合
	 */
	@Test
	public void testEnhance2() {
		List<Integer> list = new ArrayList<Integer>();
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(4);
		for (int n : list) {
			int num = n;
			System.out.println("testEnhance2--> num: " + num);

		}
	}

	/**
	 * 传统方式
	 */
	@Test
	public void testMap() {
		Map<String,String> map = new HashMap<String,String>();
		// Map map = new LinkedHashMap(); // LinkedMap是有序的
		map.put("1", "aaaa");
		map.put("2", "bbbb");
		map.put("3", "cccc");
		map.put("4", "dddd");
		// 拿到keySet,保存所有的key,通过key获取到value
		Set<String> set = map.keySet();
		Iterator<String> iterator = set.iterator();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			String value = (String) map.get(key);
			System.out.println(key + " = " + value);
		}

		// foreach
		/*for (Object key : set) {
			String value = map.get(key);
			System.out.println(key + " === " + value);
		}*/

	}

	/**
	 * 传统方式2
	 */
	@Test
	public void testMap2() {
		Map<String,String> map = new HashMap<String,String>();
		// Map map = new LinkedHashMap(); // LinkedMap是有序的
		map.put("1", "aaaa");
		map.put("2", "bbbb");
		map.put("3", "cccc");
		map.put("4", "dddd");
		// 拿到entrySet它单个的键值对存放
		Set<Entry<String, String>> set = map.entrySet();
		Iterator<Entry<String, String>> iterator = set.iterator();
		while (iterator.hasNext()) {
			Entry<String, String> entry = iterator.next();
			System.out.println(entry.getKey() + " == " + entry.getValue());
		}
		// foreach
		/*for (Entry<String, String> obj : set) {
			Entry<String, String> entry = obj;
			entry.getKey();
			System.out.println(entry.getKey() + "=== === " + entry.getValue());
		}*/
		 
	}

	/**
	 * 增强for循环需要注意的几个地方: 
	 *  1,它值适合迭代数据(取数据),而不适合修改数据,并不会修改集合的内容(大小etc)
	 *  2,需要修改集合的内容,则需要用传统的方式。
	 */
	@Test
	public void foreachTest() {
		int[] i = { 1, 2, 3, 4 };
		for (int j : i) {
			j = 10;
			System.out.println("foreach方式:" + i[1]);
		}

		for (int j = 0; j < i.length; j++) {
			System.out.print(i[j]);
			i[j] = 10;
			System.out.println(" ,传统方式修改:" + i[j]);
		}

		List<String> list = new ArrayList<String>();
		list.add("1");
		for (Object object : list) {
			object = "100";
			System.out.println(list.get(0));
		}
	}
}

上面遍历Map通过了两种方法:keySet()和entrySet()。

总结

1,foreach语句是for语句特殊情况下的增强版本,简化了编程,提高了代码的可读性和安全性(如:数组下标越界问题)。

2,相对老的for语句来说是个很好的补充。提倡能用foreach的地方就不要再用for了,提高了编程便捷性。

3,在用到对集合或者数组索引的情况下,foreach显得力不从心,这个时候是用传统的for语句的搞定。

4,foreach一般结合泛型使用。



Serdes之什么是(CDR)? 光收发器和电收发器使用的是我们所说的串行数据通信。在这种通信方式中,数据位是按顺序一个接一个地传输的。光收发器和电收发器使用的是我们所说的串行数据通信。在这种通信方式中,数据位是按顺序一个接一个地传输的。目前市场上大多数收发器都没有专用的时钟输入,因此时钟恢复和数据重新定时等功能是在收发器外部(即在主板上)进行的。接收端则需要恢复时钟以采样串行线上的数据。为了实现这一点,接收端需要一个与输入数据频率大致相同的时钟。通过使参考时钟与输入数据信号的跳变相位对齐,可以生成一个恢复的时钟。这被称为时钟恢复。 阅读详情

相关推荐

Python中的串口通信库pyserial(基础)

pyserial是一个跨平台的库,可以在多个操作系统上使用,包括Windows、Linux和MacOS。:flushInput方法用于清除输入缓冲区中的所有数据,flushOutput方法用于清除输出缓冲区中的所有待发送数据。:PySerial允许在创建Serial对象后,通过修改对象的属性来设置串口参数,如波特率、数据位、校验位和停止位。同时,也提供了方法或属性来检查串口的状态,如是否已打开。:sendBreak方法用于向串口发送一个BREAK信号,这可以用于向连接的设备发送一个中断或重置信号。

weixin_44217158的博客 1万+

详解Java中foreach、for循环语句以及实例测试

详解Java中foreach、for循环语句以及实例测试

m0_54158068的博客 5086

QMI8658姿态传感器实战:从校准到自检的完整避坑指南

本文详细解析了QMI8658姿态传感器的校准与自检流程,提供了从硬件环境搭建到高级功能开发的完整避坑指南。通过真实案例揭示电源设计、接口优化、温度补偿等关键细节,帮助开发者提升传感器精度和可靠性,适用于工业级应用场景。

weixin_29184075的博客 455

Java foreach语句的用法

Java foreach语句用法使用如何使用Java1.5出现的foreach语句foreach语句for循环foreach语句的使用注意事项 如何使用Java1.5出现的foreach语句 foreach在遍历数组、集合方面,foreach 为开发者提供了极大的方便。foreach 循环语句是 for 语句的特殊简化版本,主要用于执行遍历功能的循环。 foreach语句 foreach 循环语句的语法格式如下: for(数据类型 变量名:数组) { 需要执行的语句块; } 举一个简单的例子:

m0_56642224的博客 1万+

C#与工业设备的OPC DA/UA协议通信开发

摘要:本文介绍了C#与工业设备通信的两种OPC协议(OPC DA和OPC UA)的实现方法。OPC DA基于COM/DCOM技术,适用于Windows平台,提供实时数据采集功能;OPC UA则支持跨平台通信,具备更强的安全性和数据建模能力。文章详细展示了如何使用C#通过OPC DA和OPC UA协议读取、写入数据,并提供了代码示例,包括安装相关库、建立连接、订阅数据变化等关键步骤。这些方法为工业自动化中的设备监控与控制提供了实用解决方案。(149字)

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 1259

vTestStudio保姆教程之从0到1搭建软件环境

学习HIL测试的必经之路,保姆级教学VT从搭建到测试。

欢迎来到eee的博客 4185

java中foreach的用法

java中foreach,可以认为是增强版的for语句循环,它可以减少代码量,但是不是所有的foreach都可以代替for循环。 foreach的语句格式:for(元素类型type 元素变量value :遍历对象obj){ 引用x的java语句 } 用法1:输出一维数组 用法2:输出二维数组 foreach的局限性 foreach是for循环的增强版本,简化了编程,提高了代码的可读性和安全...

qq_44840148的博客 10万+

【ComfyUI】Wan2.2 Animate 背景保留动作迁移视频生成

本文介绍了一个基于ComfyUI的高精度视频生成工作流"Wan2.2 Animate",该系统融合动作捕捉、图像拼接和LoRA加权等技术,能自动识别人脸并完成精准动作迁移,同时保持背景稳定。工作流采用模块化设计,包含输入提取、图像融合、模型加载等关键节点,核心模型Wan2.2-Animate-14B支持fp8精度与BlockSwap控制。流程分为图像输入、动作提取、多图合成等五个阶段,通过文本提示编码器和图像语义编码器实现语义驱动的动作生成,最终输出高质量视频,适用于虚拟形象驱动和

Mr数据杨 2260

40个Java集合面试问题和答案

Java集合框架为Java编程语言的基础,也是Java面试中很重要的一个知识点。这里,我列出了一些关于Java集合的重要问题和答案。 1.Java集合框架是什么?说出一些集合框架的优点? 每种编程语言中都有集合,最初的Java版本包含几种集合类:Vector、Stack、HashTable和Array。随着集合的广泛使用,Java1.2提出了囊括所有集合接口、实现和算法的集合框架。在保证线程安

小地盘的诺克萨斯 5732

华为昇腾开发——多模型资源管理(C++)

在使用Ascend ACL(Ascend Computing Language)的ACLLite库进行多模型推理时,合理的资源管理至关重要。

如果想成为中心,那么就到中心去吧。 575

【Simulink教程案例19】基于simulink的扩频通信系统建模与仿真

扩频是一种应用于数字调制信号的调制技术,可以提高传输信号的带宽。扩频通信具有抗干扰能力强,扩频增益越大,抗干扰能力越强。而且扩频通信具有很强的保密性,扩频后信号近似白噪声,功率谱密度也很低。扩频通信可用于多址通信。扩频调制有如下三个特点:① 扩频后信号的带宽远大于信号所需的带宽② 使用扩频码进行扩频调制,扩频码与信号中的数据相互独立③ 在接收端,通过将接收信号与扩频码的同步副本进行相关,实现解扩。

FPGA/MATLAB学习教程/源码/项目合作开发 2197

Java中的for each循环

增强型for循环简化了遍历操作,提高了代码的可读性和编写效率,尤其是在不关心索引或不需要修改元素的情况下非常有效。增强型for循环,通常被称为“for-each”循环,在Java和其他支持该特性的编程语言中,提供了一种更简洁的方式来遍历数组或可迭代对象。如果需要获取集合或数组中的元素位置(索引),for-each循环无法直接提供,需使用传统for循环或结合List的indexOf()方法。for-each循环只能用于读取数据,如果需要修改集合或数组的内容,应使用传统的for循环。

全局可见 1344

Linux 命令行的艺术

Linux 命令行的艺术前言基础日常使用文件及数据处理系统调试单行脚本冷门但有用仅限 OS X 系统仅限 Windows 系统更多资源免责声明熟练使用命令行是一种常常被忽视,或被认为难以掌握的技能,但实际上,它会提高你作为工程师的灵活性以及生产力。本文是一份我在 Linux 上工作时,发现的一些命令行使用技巧的摘要。有些技巧非常基础,而另一些则相当复杂,甚至晦涩难懂。这篇文章并不长,但当你能够熟练...

AI天才研究院 9280

Java中List集合Stream流详解

java

wh柒八九的博客 2426

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

集合框架(1)Collection接口与Iterator迭代器

11> boolean retainAll(Collection coll):从当前集合中删除两个集合中不同的元素,使得当前集合仅保留与coll集合中的元素相同的元素,即当前集合中仅保留两个集合的交集,即this = this ∩ coll; boolean removeAll(Collection coll):从当前集合中删除所有与coll集合中相同的元素。boolean containsAll(Collection coll):判断coll集合中的元素是否在当前集合中都存在。

2401_88237139的博客 769

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

第七章:集合(作业)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档。

2501_93330982的博客 268

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

Java集合---02--Collection常用方法

Collection- 单列集合 Collection接口中的15个方法的使用 常用方法 add(Object e):将元素e添加到集合coll中 size():获取添加的元素的个数 addAll(Collection coll1):将coll1集合中的元素添加到当前的集合中 clear():清空集合元素 isEmpty():判断当前集合是否为空 public class CollectionTest { @Test public void test1(){

时光里的博客 302

吃透JAVA的Stream流操作,多年实践总结

好啦,关于JAVA Stream的理解要点与使用技能的阐述就先到这里啦。那通过上面的介绍,各位小伙伴们是否已经跃跃欲试了呢?快去项目中使用体验下吧!当然啦,如果有疑问,也欢迎找我一起探讨探讨咯。

Jernnifer_mao的博客 351

java中集合类forEach的用法

1、forEach介绍 先来一波源码,可以看出中国是在jdk8后出现的方法,用于做元素的for循环。 这个方法是 java.lang包下的 interface Iterable<T>的,代码如下 /** * Performs the given action for each element of the {@code Iterable} ...

qq6412110的博客 2064

java8 新特性 List,Map集合的foreach使用方法

java8 新特性list集合的foreach用法java8 foreach常用版foreachMap集合的foreach用法demo list集合的foreach用法 List<String> array= new Array<String>(); java8 foreach java8写法还是有些局限性的,循环中不能用运算符 array.forEach(list -> { System.out.println(list); }); 常用版foreach for

qq_42967728的博客 3031

MyBatis foreach 标签常用方法总结

  在 MyBatis 中,常常会遇到集合类型的参数,虽然我们可以通过 OGNL 表达式来访问集合的某一个元素,但是 OGNL 表达式无法遍历集合。foreach 标签就是专门用来解决这类问题的,foreach 标签可以用来遍历数组、列表和 Map 等集合参数,实现批量操作或一些简单 SQL 操作。  foreach 元素的属性主要有 item,index,open,separator,close,collection。各属性含义如下所示。  集合中元素迭代时的别名,该参数为必选。  在 list 和数组中

长安明月的博客 1万+

foreach的用法

foreach遍历数组和集合 格式: for(元素类型 元素变量x:遍历对象(数组或集合)){ 引用元素变量x的语句; } 例: int[] array = new int[5]; for(int x : array){ System.out.println(x); } 遍历MAP集合格式如下: for (Map.Entry<K, V> entry : map.entrySet()) action.accept(entry.getKey(), entry.getValue());

weixin_43151557的博客 4万+

foreach用法

总之,foreach 是一种非常实用的语法糖,可以使代码更简洁、更易读,提高代码的可维护性和可读性。要注意,在迭代过程中,由于 foreach 遍历的是集合对象的副本,而非原始集合对象,因此如果在循环内部修改集合元素,则不会影响原始集合。如果需要修改集合元素,可以考虑使用迭代器 Iterator 进行操作。其中 element 表示集合中的元素,collection 表示要遍历的集合,循环体中的代码会执行若干次,每次都会取出 collection 中的一个元素,赋值给 element,然后运行循环体。

weixin_51378457的博客 1万+

为什么不能在foreach循环中修改集合?

阿里巴巴JAVA开发手册》中有这样一条:不要在 foreach 循环里进行元素的 add / remove 操作,remove 元素使用 Iterator 方式。经测试,当在 foreach 循环中 add / remove 集合元素,可能会抛出 ConcurrentModificationException 异常,下面介绍进行详细说明。

zhhui1123的博客 2217

Java中List的forEach用法详解

java复制下载// 对每个元素进行平方操作// 输出:1 4 9 16 25});

BillKu的博客 2189

JAVA之forEach遍历集合

JAVA之forEach遍历集合 在JDK 8中,根据Lambda表达式的特性还增加了一个forEach(Consumer action)方法来遍历集合,该方法所需要的参数是一个函数式接口 import java.util.ArrayList; import java.util.List; public class forEachTest01 { public static void main(String[] args) { //创建ArrayList集合 L

HR的博客 4493
上一篇: Eclipse快捷键与使用技巧总结
下一篇: 总结过去10年的程序员生涯
池哥搬砖
博客等级 码龄17年 255粉丝 10原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值