处理的数据量>10000条的时候不推荐使用双重for循环处理
1.数据量≈10000时候 以下代码处理的时间大约为170ms
public static void main(String[] args) {
List<Dog> dogList = new ArrayList<>();
List<Cat> catList = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
if (i / 3 == 0) {
dogList.add(new Dog("狗狗" + i, "黑白色" + i));
catList.add(new Cat("咪咪" + i, "橘黄色" + i));
} else if (i / 5 == 0) {
dogList.add(new Dog("狗狗" + i, "黑色" + i));
catList.add(new Cat("咪咪" + i, "黑白色" + i));
} else {
dogList.add(new Dog("狗狗" + i, "橘黄色" + i));
catList.add(new Cat("咪咪" + i, "白色" + i));
}
}
//System.out.println(dogList.size()+" "+catList.size());
//
long startTime = System.currentTimeMillis();
for (Dog dog : dogList) {
System.out.println(dog.getName());
for (Cat cat : catList) {
if (dog.getColorl().equals(cat.getColorl())) {
//具体业务逻辑
break;
}
}
}
//manage2(dogList,catList);
long endTime = System.currentTimeMillis();
System.out.println("总耗时:" + (endTime - startTime) + "毫秒");
}
如果采用for+map循环的话为57ms
2.将数据量变为100000时候差别就巨大了
双重for循环处理时间大约为120000ms
for+map处理时间 为100ms 相差大于1200倍巨大
下面为for+map写法
Map<String,Cat> catMap = catList.stream().collect(Collectors.toMap(Cat::getColorl,Function.identity()));
for(Dog dog : dogList){
if(catMap.containsKey(dog.getColorl())){
//具体业务逻辑
break;
}
}