1 import com.google.common.collect.Lists; 2 import org.junit.Test; 3 4 import java.util.List; 5 import java.util.stream.Collectors; 6 7 /** 8 * 9 */ 10 public class Demo { 11 12 @Test 13 public void test() throws InterruptedException { 14 // int size = 5000000; 15 int size = 50000000; 16 17 Thread.sleep(1000); 18 19 long t1s = System.currentTimeMillis(); 20 List<Integer> list1 = Lists.newArrayListWithExpectedSize(size); 21 for (int i = 0; i < size; i++) { 22 list1.add(i + 1); 23 } 24 long t1e = System.currentTimeMillis(); 25 System.out.println("for 循环 耗时:" + (t1e - t1s) + " , size = " + list1.size()); 26 27 28 long t2s = System.currentTimeMillis(); 29 List<Integer> list2 = Lists.newArrayListWithExpectedSize(size); 30 list1.forEach( 31 i -> list2.add(i + 1) 32 ); 33 long t2e = System.currentTimeMillis(); 34 System.out.println("foreach 耗时:" + (t2e - t2s) + " , size = " + list2.size()); 35 36 37 long t3s = System.currentTimeMillis(); 38 List<Integer> list3 = list1.stream().map(i -> i + 1).collect(Collectors.toList()); 39 long t3e = System.currentTimeMillis(); 40 System.out.println("stream 耗时:" + (t3e - t3s) + " , size = " + list3.size()); 41 42 Thread.sleep(1000); 43 } 44 45 46 }
测试结果: