java利用map降低时间复杂度@mapkey

39 篇文章 0 订阅

最近做了一个项目,因为涉及多个表,所以有大量的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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值