Java8 ArrayList之forEach

之前使用Java8、顺便整理自己学到的一些
一、用法
常用写法

for (String str : list){
	System.out.println(str);
}

Java8中

list.forEach(str-> System.out.println(str));
list.forEach(str-> {});//{}中可以写逻辑

代码看上去更简洁

二、效率

public static void main(String[] args) {
    List list = new ArrayList<>();
    for (int i=0;i<1000000;i++){
        list.add("str"+i);
    }
    for1(list);
    for2(list);
    for3(list);
    for4(list);
}
public static void for1(List list){
    long startTime = System.currentTimeMillis();
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < list.size(); i++) {
        stringBuilder.append(list.get(i));
    }
    long endTime = System.currentTimeMillis();
    System.out.println("for1 execute time : "+(endTime-startTime) +" ms");
}
public static void for2(List list){
    long startTime = System.currentTimeMillis();
    StringBuilder stringBuilder = new StringBuilder();
    for (String str : list){
        stringBuilder.append(str);
    }
    long endTime = System.currentTimeMillis();
    System.out.println("for2 execute time : "+(endTime-startTime) +" ms");
}
public static void for3(List list){
    long startTime = System.currentTimeMillis();
    StringBuilder stringBuilder = new StringBuilder();
    list.forEach(c -> {
        stringBuilder.append(c);
    });
    long endTime = System.currentTimeMillis();
    System.out.println("for3 execute time : "+(endTime-startTime) +" ms");
}
public static void for4(List list){
    long startTime = System.currentTimeMillis();
    StringBuilder stringBuilder = new StringBuilder();
    list.stream().forEach(c -> {
        stringBuilder.append(c);
    });
    long endTime = System.currentTimeMillis();
    System.out.println("for4 execute time : "+(endTime-startTime) +" ms");
}

执行结果:

for1 execute time : 33 ms
for2 execute time : 52 ms
for3 execute time : 78 ms
for4 execute time : 37 ms

结果分析:
虽然forEach使代码看上去更简洁,但是从效率上看却是相反的,最原始的循环效率最高,操作越方便的反而性能会下降,操作越方便的方法其内部都是层层调用

default void forEach(Consumer action) {
	 Objects.requireNonNull(action);
	 for (T t : this) {
	 	 action.accept(t);
	 }
}

至于list.stream().forEach听说它可以支持多线程并行操作。

文章仅作为个人学习整理~

你可能感兴趣的:(Java)