1、初始生成字符串的代码程序:
package com.map.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
/**
* @param args
*/
public static List<Map<String, String>> maps = new ArrayList<Map<String,String>>();
static{
Map m1 = new HashMap<String, String>();
m1.put("total", "10");
m1.put("createTime", "2014-10-18");
maps.add(m1);
Map m2 = new HashMap<String, String>();
m2.put("total", "20");
m2.put("createTime", "2014-10-15");
maps.add(m2);
Map m3 = new HashMap<String, String>();
m3.put("total", "30");
m3.put("createTime", "2014-10-19");
maps.add(m3);
Map m4 = new HashMap<String, String>();
m4.put("total", "40");
m4.put("createTime", "2014-10-17");
maps.add(m4);
Map m5 = new HashMap<String, String>();
m5.put("total", "50");
m5.put("createTime", "2014-10-16");
maps.add(m5);
Map m6 = new HashMap<String, String>();
m6.put("total", "60");
m6.put("createTime", "2014-10-20");
maps.add(m6);
Map m7 = new HashMap<String, String>();
m7.put("total", "70");
m7.put("createTime", "2014-10-21");
maps.add(m7);
}
2、main方法调用拼接的方法
/**
*
* @param args main方法调用拼接的方法
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
sortList(maps);
getTimeString();
getTotalString();
}
3、将程序进行排序
package com.map.test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.Map;
public class ReportCompare implements Comparator<Map<String, String>> {
@Override
public int compare(Map<String, String> o1, Map<String, String> o2) {
String o1Time = o1.get("createTime");
String o2Time = o2.get("createTime");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date o1D = sdf.parse(o1Time);
Date o2D = sdf.parse(o2Time);
if (o1D.before(o2D)) {
return -1;
}else if (o1D.equals(o2D)) {
return 0;
}else if (o1D.after(o2D)) {
return 1;
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 2;
}
}
4、拼接字符串
public static void getTimeString() {
StringBuffer sb = new StringBuffer("[");
for (Map<String, String> map : maps) {
sb.append("'"+map.get("createTime")+"',");
}
sb.deleteCharAt(sb.length()-1);
sb.append("]");
System.out.println(sb.toString());
}
public static void getTotalString() {
StringBuffer sb = new StringBuffer("[");
for (Map<String, String> map : maps) {
sb.append(map.get("total")+",");
}
sb.deleteCharAt(sb.length()-1);
sb.append("]");
System.out.println(sb.toString());
}
public static List<Map<String, String>> sortList(List<Map<String, String>> maps){
Collections.sort(maps, new ReportCompare());
return maps;
}
}