Java里面遍历list的方式

问题:Java里面遍历list的方式

对于Java语言有点陌生,我尝试熟悉遍历list(或者其他集合)的所有方法(或者是其他正确的语法)和它们每一个方法的优缺点

给定 List的list对象,我知道有下列方法去循环所有的元素

基于循环的(当然这也等价于while/do while循环)

// 不推荐哈,看下面
for (int i = 0; i < list.size(); i++) {E element = list.get(i);// 1 - 可以调用元素的方法// 2 - 可以使用i去做一些基于下标的方法调用// ...
}

循环的增强版本 (很好地回答了这个问题)

for (E element : list) {// 1 - 调用元素的方法// ...
}

迭代器

for (Iterator<E> iter = list.iterator(); iter.hasNext(); ) {E element = iter.next();// 1 - 调用元素的方法// 2 - 可以用 iter.remove() 方法从list上移除当前元素// ...
}

List迭代器

for (ListIterator<E> iter = list.listIterator(); iter.hasNext(); ) {E element = iter.next();// 1 - 调用元素的方法// 2 - 可以用 iter.remove() 方法从list上移除当前元素// 3 - 可以用 iter.add(...) 在当前元素和下一个元素之间插入新元素// 4 -可以用iter.set(...) 取代当前元素// ...
}

Java函数

list.stream().map(e -> e + 1); // 可以对e用一个转换函数

Iterable.forEach, Stream.forEach, …

(来自Java的stream API的映射方法 )

在Java8集合实现了 Iterable接口的类型(例如所有的list)里面,都要一个forEach的方法,可以代替上面的循环语句使用了(提供一个优秀的对比那就是另一个问题了)

Arrays.asList(1,2,3,4).forEach(System.out::println);
// 1 - 调用元素的方法
// 2 - 需要一个里面元素的引用用来移除它们
//   
// 3 - 从功能上分离迭代和发生在每一个元素上的行为Arrays.asList(1,2,3,4).stream().forEach(System.out::println);
// Same capabilities as above plus potentially greater utilization of parallelism
//  实现相同的功能,上面的更加好,因为使用了并行
// 注意:因此,执行的顺序是不能保证的
// 想了解更多关于这个的请看 [Stream.forEachOrdered][stream-foreach-ordered] 

还有任何的其他方法吗?
(顺便说一下,我不是对提升性能感兴趣。作为一个开发人员,我只是想知道什么方式是可用的而已)

回答

一种JDK8风格的迭代:

public class IterationDemo {public static void main(String[] args) {List<Integer> list = Arrays.asList(1, 2, 3);list.stream().forEach(elem -> System.out.println("element " + elem));}
}

文章翻译自Stack Overflow:https://stackoverflow.com/questions/18410035/ways-to-iterate-over-a-list-in-java

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/390995.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python 重启内核_Python从零开始的内核回归

python 重启内核Every beginner in Machine Learning starts by studying what regression means and how the linear regression algorithm works. In fact, the ease of understanding, explainability and the vast effective real-world use cases of linear regression is…

bzoj千题计划282:bzoj4517: [Sdoi2016]排列计数

http://www.lydsy.com/JudgeOnline/problem.php?id4517 组合数错排公式 #include<cstdio> #include<iostream>using namespace std;#define N 1000001const int mod1e97;long long fac[N],inv[N],f[N];void read(int &x) {x0; char cgetchar();while(!isdigit…

chrome启用flash_如何在Google Chrome中启用Adobe Flash Player

chrome启用flashRemember Adobe Flash player? Its that nifty software that lets websites embed videos and web games. Whole websites can even be powered by Flash.还记得Adobe Flash Player吗&#xff1f; 正是这些漂亮的软件使网站可以嵌入视频和网络游戏。 整个网站…

怎么样把Java的字符串转化为字节数组?

问题&#xff1a;怎么样把Java的字符串转化为字节数组 有没有任何方法把Java的字符串转化为字节数组 我尝试这样: System.out.println(response.split("\r\n\r\n")[1]); System.out.println("******"); System.out.println(response.split("\r\n\r\…

Forward团队-爬虫豆瓣top250项目-模块开发过程

项目托管平台地址:https://github.com/xyhcq/top250 开发模块功能: 写入文件功能 开发时间:3小时 实现将爬取到的信息写入到文件中的功能 实现过程&#xff1a; # 打开文件 fopen("top250.txt","w") 在别的队员写的代码基础上&#xff0c;加入功能代码 de…

CSS3 outline-offset 属性 项目中input会遇到

outline在一个声明中设置所有的轮廓属性。outline:颜色&#xff08;outline-line&#xff09;样式&#xff08;outline-style&#xff09;宽度&#xff08;outline-width&#xff09; outline-offset 属性对轮廓进行偏移&#xff0c;并在边框边缘进行绘制。 轮廓在两方面与边框…

回归分析中自变量共线性_具有大特征空间的回归分析中的变量选择

回归分析中自变量共线性介绍 (Introduction) Performing multiple regression analysis from a large set of independent variables can be a challenging task. Identifying the best subset of regressors for a model involves optimizing against things like bias, multi…

winform窗体模板_如何验证角模板驱动的窗体

winform窗体模板介绍 (Introduction) In this article, we will learn about validations in Angular template-driven forms. We will create a simple user registration form and implement some inbuilt validations on it. Along with the inbuilt validations, we will a…

【loj6191】「美团 CodeM 复赛」配对游戏 概率期望dp

题目描述 n次向一个栈中加入0或1中随机1个&#xff0c;如果一次加入0时栈顶元素为1&#xff0c;则将这两个元素弹栈。问最终栈中元素个数的期望是多少。 输入 一行一个正整数 n 。 输出 一行一个实数&#xff0c;表示期望剩下的人数&#xff0c;四舍五入保留三位小数。 样例输入…

查找满足断言的第一个元素

问题&#xff1a;查找满足断言的第一个元素 我刚刚开始使用Java 8的lambdas&#xff0c;我尝试去实现一些我在函数式语言里面经常用的 例如&#xff0c;大部分的函数式语言里有一些查找函数&#xff0c;针对序列或者list进行操作&#xff0c;返回使得断言为真的第一个元素。我…

Lock和synchronized的选择

学习资源:http://www.cnblogs.com/dolphin0520/p/3923167.html 一.java.util.concurrent.locks包下常用的类 1.Lock public interface Lock { void lock();//用来获取锁。如果锁已被其他线程获取&#xff0c;则进行等待。void lockInterruptibly() throws InterruptedException…

python 面试问题_值得阅读的30个Python面试问题

python 面试问题Interview questions are quite tricky to predict. In most cases, even peoples with great programming ability fail to answer some simple questions. Solving the problem with your code is not enough. Often, the interviewer will expect you to hav…

spring boot中 使用http请求

因为项目需求&#xff0c;需要两个系统之间进行通信&#xff0c;经过一番调研&#xff0c;决定使用http请求。服务端没有什么好说的&#xff0c;本来就是使用web 页面进行访问的&#xff0c;所以spring boot启动后&#xff0c;controller层的接口就自动暴露出来了&#xff0c;客…

arduino joy_如何用Joy开发Kubernetes应用

arduino joyLet’s face it: Developing distributed applications is painful.让我们面对现实&#xff1a;开发分布式应用程序很痛苦。 Microservice architectures might be great for decoupling and scalability but they are intimidatingly complex when it comes to de…

怎么样得到平台相关的换行符?

问题&#xff1a;怎么样得到平台相关的换行符&#xff1f; Java里面怎么样得到平台相关的换行符。我不可能到处都用"\n" 回答一 In addition to the line.separator property, if you are using java 1.5 or later and the String.format (or other formatting me…

scrapy常用工具备忘

scrapy常用的命令分为全局和项目两种命令&#xff0c;全局命令就是不需要依靠scrapy项目&#xff0c;可以在全局环境下运行&#xff0c;而项目命令需要在scrapy项目里才能运行。一、全局命令##使用scrapy -h可以看到常用的全局命令 [rootaliyun ~]# scrapy -h Scrapy 1.5.0 - n…

机器学习模型 非线性模型_机器学习:通过预测菲亚特500的价格来观察线性模型的工作原理...

机器学习模型 非线性模型Introduction介绍 In this article, I’d like to speak about linear models by introducing you to a real project that I made. The project that you can find in my Github consists of predicting the prices of fiat 500.在本文中&#xff0c;…

NOIP赛前模拟20171027总结

题目&#xff1a; 1.寿司 给定一个环形的RB串要求经过两两互换后RB分别形成两段连续区域,求最少操作次数(算法时间O(n)) 2.金字塔 给定一个金字塔的侧面图有n层已知每一层的宽度高度均为1要求在图中取出恰好K个互不相交的矩形&#xff08;边缘可以重叠&#xff09;,求最多可以取…

虚幻引擎 js开发游戏_通过编码3游戏学习虚幻引擎4-5小时免费游戏开发视频课程

虚幻引擎 js开发游戏One of the most widely used game engines is Unreal Engine by Epic Games. On the freeCodeCamp.org YouTube channel, weve published a comprehensive course on how to use Unreal Engine with C to develop games.Epic Games的虚幻引擎是使用最广泛的…

建造者模式什么时候使用?

问题&#xff1a;建造者模式什么时候使用&#xff1f; 建造者模式在现实世界里面的使用例子是什么&#xff1f;它有啥用呢&#xff1f;为啥不直接用工厂模式 回答一 下面是使用这个模式的一些理由和Java的样例代码&#xff0c;但是它是由设计模式的4个人讨论出来的建造者模式…