前言
最近和工作了两年多的朋友聊天,发现他竟然不知道如何编写双层For循环才能提升性能。所以特此分享出来,希望对大家有所帮助,这个在工作中非常实用!
视频链接
代码示例
package com.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 双层For循环
*/
public class TestAll {
public static void main(String[] args) {
List<A> aList = getAList();
List<B> bList = getBList();
//使用双层for循环
//int count = useFor(aList,bList);
//使用stream转Map形式
int count = useStreamMap(aList,bList);
System.out.println("循环次数:" + count);
}
public static int useFor(List<A> aList,List<B> bList){
int index = 0;
//遍历A
for (A a : aList) {
List<B> bListNew = new ArrayList<>();
//遍历B
for (B b : bList) {
index++;
if(a.getKey()==b.getKey()){
bListNew.add(b);
}
}
//设置A的bList
a.setbList(bListNew);
}
return index;
}
public static int useStreamMap(List<A> aList,List<B> bList){
int index = 0;
//判断bList空指针
if (null==bList) {
return index;
}
//将bList转成map形式 key-value
List<B> newBList = new ArrayList<>();
Map<Integer, List<B>> bListMap = newBList.stream().collect(Collectors.groupingBy(B::getKey));
index += bList.size();
for (A a : aList) {
index++;
List<B> bItemList = bListMap.get(a.getKey());
//判断bListMap查找的结果是否为空
if (null!=bItemList) {
a.setbList(bItemList);
}
}
// N * N
// N + N
return index;
}
public static List<A> getAList(){
//模拟SQL查询结果
List<A> aList = new ArrayList<>();
aList.add(new A(0,"订单0"));
aList.add(new A(1,"订单1"));
aList.add(new A(2,"订单2"));
aList.add(new A(3,"订单3"));
return aList;
}
public static List<B> getBList(){
//模拟SQL查询结果
List<B> bList = new ArrayList<>();
bList.add(new B(1,11,"商品-衣服-蓝色"));
bList.add(new B(1,12,"商品-裤子-白色"));
bList.add(new B(2,21,"商品-鞋子"));
bList.add(new B(2,22,"商品-帽子"));
bList.add(new B(3,31,"商品-手表"));
return bList;
}
}
//主单 一个订单肯定有多条商品明细
class A {
private int key;
private String str2;
private List<B> bList;
public A(int key, String str2) {
this.key = key;
this.str2 = str2;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public String getStr2() {
return str2;
}
public void setStr2(String str2) {
this.str2 = str2;
}
public List<B> getbList() {
return bList;
}
public void setbList(List<B> bList) {
this.bList = bList;
}
}
//商品明细
class B {
private int key;
private int detailId;
private String str1;
public B(int key, int detailId, String str1) {
this.key = key;
this.detailId = detailId;
this.str1 = str1;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public int getDetailId() {
return detailId;
}
public void setDetailId(int detailId) {
this.detailId = detailId;
}
public String getStr1() {
return str1;
}
public void setStr1(String str1) {
this.str1 = str1;
}
}