Java中使用Map对象进行数据分组

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

     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<String,StringBuffer> dataMap = new HashMap<String, StringBuffer>();
		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("<option><dm>"+C+"</dm><mc>"+D+"</mc><pc>"+A+"</pc></option>");
				}else{
					StringBuffer buffer = new StringBuffer();
					buffer.append("<option><dm>"+C+"</dm><mc>"+D+"</mc><pc>"+A+"</pc></option>");
					dataMap.put(bufferIndex, buffer);
				}
			}
			Set<String> keySet = dataMap.keySet();
			Iterator<String> it = keySet.iterator();
			while(it.hasNext()){
				String index = it.next();
				//处理语句
				Helper.saveFile(null, root+index+".xml", "<?xml version=\"1.0\" encoding=\"utf-8\" ?><root><select>"+dataMap.get(index).toString()+"</select></root>");
			}
			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<partslen-1;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();
		}
	}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值