java map分组_Java中使用Map对象进行数据分组

通过数据库的分组函数,我们可以很轻易的对数据进行分组。如果要在Java内对查到的分组数据进行处理(不对数据库发出多次查询)。那就可以使用Map对象来处理。将分组关键字段的值作为索引key,entry为一个List或Stringbuffer对象。将内容不断累加到相应的List或Stringbuffer中。最后遍历Map对象取出List或Stringbuffer的内容即可。

XmlGenarator.java

public class XmlGenerator{

@SuppressWarnings("rawtypes")

public static void main(String[] argc){

String resource = "META-INF/conf/mybatis-config.xml";

String root = "D:/xml/";

InputStream inputStream;

String A="",B="",C="",D="";

HashMap dataMap = new HashMap();

try {

inputStream = Resources.getResourceAsStream(resource);

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

SqlSession session = sqlSessionFactory.openSession();

List lists = session.selectList("com.example.service.getData");

for(Object o:lists){

Map map = (Map) o;

A =(String)map.get("A");

B =(String)map.get("B");

C =(String)map.get("C");

D =(String)map.get("D");

String bufferIndex =A+"_"+B;

if(dataMap.containsKey(bufferIndex)){

dataMap.get(bufferIndex).append(""+C+""+D+""+A+"");

}else{

StringBuffer buffer = new StringBuffer();

buffer.append(""+C+""+D+""+A+"");

dataMap.put(bufferIndex, buffer);

}

}

Set keySet = dataMap.keySet();

Iterator it = keySet.iterator();

while(it.hasNext()){

String index = it.next();

//处理语句

Helper.saveFile(null, root+index+".xml", "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"+dataMap.get(index).toString()+"");

}

session.close();

}catch (IOException e) {

e.printStackTrace();

}

}

}

Helper.java

public class Helper {

public static void saveFile(String savePalce,String fileName,String context) throws IOException{

if(savePalce!=null){

File dir = new File(savePalce);

if(!dir.exists()){dir.mkdirs();}

}

if(fileName!=null){

String[] parts = fileName.split("/");

int partslen = parts.length,i;

StringBuffer dirName = new StringBuffer();

for(i=0;i

dirName.append(parts[i]+"/");

}

File dir = new File(dirName.toString());

if(!dir.exists()) {dir.mkdirs();}

File file = new File(fileName);

if(!file.exists()) {file.createNewFile();}

FileOutputStream out=new FileOutputStream(file,false);

if(context!=null){

out.write(context.getBytes("utf-8"));

}

out.close();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值