测试代码如下:
package com.mew.kittyapi.test.lamda;
import java.util.ArrayList;
import java.util.List;
/**
* @author yanhu
* @version 2019/4/9 下午 12:02
*/
public class LambdaMain {
public static void main(String[] args) {
int size = 1000000;
long st;
List<Integer> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
list.add(i);
}
st = System.currentTimeMillis();
new ArrayList<String>(0).forEach(s -> {
});
System.out.println("lambda init: " + (System.currentTimeMillis() - st) + "ms");
st = System.currentTimeMillis();
Integer max1 = forMax(list);
System.out.println("for: " + (System.currentTimeMillis() - st) + "ms, max: " + max1);
st = System.currentTimeMillis();
Integer max2 = foreachMax(list);
System.out.println("foreach: " + (System.currentTimeMillis() - st) + "ms, max: " + max2);
st = System.currentTimeMillis();
Integer max3 = lambdaMax(list);
System.out.println("lambda: " + (System.currentTimeMillis() - st) + "ms, max: " + max3);
}
/**
* 使用正常for循环
*
* @param array
* @return
*/
private static Integer forMax(List<Integer> array) {
Integer max = 0;
int size = array.size();
Integer it;
for (int i = 0; i < size; i++) {
it = array.get(i);
if (it > max) {
max = it;
}
}
return max;
}
/**
* 使用增强for循环
*
* @param array
* @return
*/
private static Integer foreachMax(List<Integer> array) {
Integer max = 0;
for (Integer it : array) {
if (it > max) {
max = it;
}
}
return max;
}
static Integer max = 0;
/**
* 使用lambda表达式
*
* @param array
* @return
*/
private static Integer lambdaMax(List<Integer> array) {
array.forEach(it -> {
if (it > max) {
max = it;
}
});
return max;
}
}
执行结果: