User类
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
int id;
String name;
int sex;
int age;
}
测试类
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.time.temporal.TemporalField;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class TestController {
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
for (int i = 0; i < 100; i++) {
int sex = 0;
if ((i & 1) == 1) {
sex = 1;
}
User user = User.builder().id(i).name("刘-" + i).sex(sex).age(i).build();
userList.add(user);
}
System.out.println("=====数据总量:" + userList.size());
long beginTime = System.currentTimeMillis();
int sumAge1 = 0;
for (User user : userList) {
sumAge1 += user.getAge();
}
long endTime = System.currentTimeMillis();
System.out.println("=====增强for循环所用时间 " + (endTime - beginTime) + " 毫秒" + " ,计算结果" + sumAge1);
beginTime = System.currentTimeMillis();
int sumAge2 = userList.stream().collect(Collectors.summingInt(User::getAge));
endTime = System.currentTimeMillis();
System.out.println("=====顺序流所用时间 " + (endTime - beginTime) + " 毫秒, 计算结果" + sumAge2);
beginTime = System.currentTimeMillis();
int sumAge = userList.parallelStream().mapToInt(User::getAge).sum();
endTime = System.currentTimeMillis();
System.out.println("=====并行流所用时间 " + (endTime - beginTime) + " 毫秒, 计算结果" + sumAge);
}
}
测试结果:
一千五百万的时候并行流最快
到20000000就内存溢出了。
所以通常的处理逻辑for循环性能更优。