本篇內容主要講解“java的for()、增強for()、foreach()、stream().foreach()有什么區別”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“java的for()、增強for()、foreach()、stream().foreach()有什么區別”吧!
測試一
public class TestFor {
private static void doSome(String s) {
}
public static void main(String[] args) {
/*添加數據*/
List<String> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add("第" + i + "條數據");
}
/*for循環*/
long st1 = System.currentTimeMillis();
for (int i = 0; i < list.size(); i++) {
doSome(list.get(i));
}
/*增強for循環*/
long st2 = System.currentTimeMillis();
for (String s : list) {
doSome(s);
}
/*foreach*/
long st3 = System.currentTimeMillis();
list.forEach(s -> doSome(s));
/*stream.foreach*/
long st4 = System.currentTimeMillis();
list.stream().forEach(s -> doSome(s));
long st5 = System.currentTimeMillis();
print(st1, st2, st3, st4, st5);
}
/*時間輸出*/
public static void print(long s1, long s2, long s3, long s4, long s5) {
System.out.println("for 循環: " + (s2 - s1) + "ms");
System.out.println("增強for 循環: " + (s3 - s2) + "ms");
System.out.println("foreach 循環:" + (s4 - s3) + "ms");
System.out.println("stream.foreach循環:" + (s5 - s4) + "ms");
}
}結果:
for 循環: 0ms 增強for 循環: 0ms foreach 循環:129ms stream.foreach循環:3ms
測試二
List<String> list = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
list.add("第" + i + "條數據");
}結果:
for 循環: 1ms 增強for 循環: 1ms foreach 循環:121ms stream.foreach循環:3ms
測試三
List<String> list = new ArrayList<>();
for (int i = 0; i < 1000000; i++) {
list.add("第" + i + "條數據");
}結果:
for 循環: 17ms 增強for 循環: 23ms foreach 循環:165ms stream.foreach循環:18ms
測試四
private static void doSome(String s) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}結果:
for 循環: 184ms 增強for 循環: 169ms foreach 循環:224ms stream.foreach循環:116ms
到此,相信大家對“java的for()、增強for()、foreach()、stream().foreach()有什么區別”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。