最近做了一个项目,因为涉及多个表,所以有大量的list,就产生了大量的for循环。这样的话时间复杂度就蹭蹭蹭的上去了。两个for循环的嵌套的时间复杂度就是n的平方了。
需求:现在需要查出来两个结果list,list1和list2,然后list中分别存储了各自的对象,对象中的channelid做比较,如果相同,就做进一步的操作。但是这样的话问题就出现了,两个for循环,算法的时间复杂度为n的平方。如何降低复杂度呢,我使用了mybaits的map,直接使用channelid作为key,相应的对象作为value值即可。这样遍历list1是,就可以使用该对象的channelid作为map2的key获取其对应的对象了。(注意:原来的list2现在这里变成了map2)
这样复杂度就变成了n
上代码。
原来两个for循环的代码:controller层
List<Channel> channelList = channelServiceImpl.batchQueryById(orgCardPerformanceProportionList);
for (Channel channel : channelList){
for(OrgCardPerformanceProportion temp : orgCardPerformanceProportionList){
if(temp.getChannelId().intValue() == channel.getId().intValue()){
temp.setChannelCode(channel.getChannelCode());
temp.setChannelName(channel.getChannelName());
}
}
}
优化之后的代码:controller层
Map<String, Channel> channelMap = channelServiceImpl.batchQueryById(orgCardPerformanceProportionList);
for (OrgCardPerformanceProportion temp : orgCardPerformanceProportionList) {
Integer channelId = temp.getChannelId();
if (channelId != null) {
Channel channel = channelMap.get(channelId);
if (channel != null) {
temp.setChannelCode(channel.getChannelCode());
temp.setChannelName(channel.getChannelName());
}
}
}
dao层
package com.cmbc.cms.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Param;
import com.cmbc.cms.module.Channel;
import com.cmbc.dataplatform.datasource.DataSource;
/**
* Created by xiazhixin on 2018/8/3.
*/
@DataSource("menhuDataSource")
public interface ChannelMapper {
/**
*
* @param record
* @return
*/
@MapKey("id")
<T> Map<String, Channel> batchQueryById(
@Param("list") List<T> list
);
}
mapper层:
<resultMap id="BaseResultMap" type="com.cmbc.cms.module.Channel">
<id column="ID" jdbcType="INTEGER" property="id" />
<result column="Channel" jdbcType="VARCHAR" property="channelCode" />
<result column="ChannelName" jdbcType="VARCHAR" property="channelName" />
</resultMap>
<select id="batchQueryById" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from OnlineChannel
<where>
and id in
<foreach collection="list" item="item" open="(" close=")" separator=",">
#{item.channelId,jdbcType=INTEGER}
</foreach>
</where>
</select>