Hi friends, I'm sharing little code here, this might help you to find fastest way to iterate Java ArrayList.
I'm using JDK 8.
You need a timer to print the time elapsed since timer is started.
This timer might not 100% accurate but will help to choose correct iterator method.
File 1 : CustomTimer.java
This timer might not 100% accurate but will help to choose correct iterator method.
File 1 : CustomTimer.java
package com.raju.demo; public class CustomTimer { private long startTime = 0l; public CustomTimer() { this.startTime = System.currentTimeMillis(); } public void stop(String msg) { long totalTime = (System.currentTimeMillis() - startTime); String logMessage = null; if (null == msg) { logMessage = "##End time : " + totalTime + " ms"; } else { logMessage = "##End time : " + totalTime + " ms for class/method : " + msg; } System.out.println(logMessage); } }
File 2: Main.java
package com.raju.demo; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Main { public static void main(String... args) { List<Integer> myList = new ArrayList<>(); CustomTimer customTimer = new CustomTimer(); for (int x = 0; x < 10000000; x++) { myList.add(x); } customTimer.stop("After List Creation"); customTimer = new CustomTimer(); for (int i = 0, size = myList.size(); i < size; i++) { Integer s = myList.get(i); } customTimer.stop("After Traditional for"); customTimer = new CustomTimer(); for (Integer s : myList) { } customTimer.stop("After foreach"); customTimer = new CustomTimer(); Iterator<Integer> iterator = myList.iterator(); while (iterator.hasNext()) { iterator.next(); } customTimer.stop("After Iterator"); customTimer = new CustomTimer(); myList.stream().forEach((value) -> { // System.out.println(value); }); customTimer.stop("After new stream collection"); } }
##End time : 3247 ms for class/method : After List Creation ##End time : 95 ms for class/method : After Traditional for ##End time : 172 ms for class/method : After foreach ##End time : 124 ms for class/method : After Iterator ##End time : 141 ms for class/method : After new stream collection
You might want to run this few more times !.
If you want to try LinkedList then you should not use traditional for loop !!
Thanks for reading.