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.pswp.cn/news/390995.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390995.shtml
英文地址,請注明出處:http://en.pswp.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個人討論出來的建造者模式…