需求说明:A list假如是一串编码,
通过in的sql语句可以查到一连串另外的数据(List<B> = select (A list); ),但查出来的数据(List<B>)是按数据库的自然顺序进行排序的,无法与原来的list(A List)对应,也就是说
无法做到A、B、C进去a、b、c出来,而是变成其他顺序出来,所以需要对出来的数据进行重新排序。
环境:java8以上
示例代码如下:
public AccountResultData accountMoneyRegion(AccountResultData accountResultData, Map<String, Object> continueMap,
List<String> nameList, List<String> codeList, String year) {
List<String> barAreaData = new ArrayList<>();
Map<String, Object> map = new HashMap<>(continueMap);//创建用于查询用的map
map.put("type", "2");//添加参数
map.put("codeList", codeList);//这就是上面提到的A list
map.put("time", year);
List<TakeAccountRegion> takeAccountRegionList = takeAccountRegionMapper.selectByTypeAndCodeList(map);//将map传入sql层内查询出List<B>
//此处便出现了List<B>与A list不能一一对应的情况
//下面就是解决方法:
Map<String,TakeAccountRegion> takeAccountRegionMap = takeAccountRegionList.stream().collect(
Collectors.toMap(a -> a.getRegionCode(),
a -> a));
for(String code:codeList) {
barAreaData.add(MoneyUtils.matchMonmey(takeAccountRegionMap.get(code).getTotalMoneny()).toString());
}
accountResultData.setBarAreaData(barAreaData);
accountResultData.setAreaYAxisData(nameList);
return accountResultData;
}
其中关键性的代码:
Map<String,TakeAccountRegion> takeAccountRegionMap = takeAccountRegionList.stream().collect(
Collectors.toMap(a -> a.getRegionCode(),
a -> a));
怎么理解这段代码呢?首先声明了一个String,某对象(这里是:TakeAccountRegion)的map,必须保证key是唯一值:
这里就是a.getRegionCode()这里,a就是对象它本身
然后再通过循环,用之前的list,来从这个map里取值即可。
此处牵扯到了JAVA 8 新特性:Lambda表达式
关于JAVA 8 新特性 可以参考:https://blog.csdn.net/u014470581/article/details/54944384
当然,我是菜鸡,如果有更好的方法,请大佬们多多指导我