【java】Comparator的用法 :具体参考/u012250875/article/details/55126531/
这两种其实都差不多,只是匿名内部类的不同写法而已。项目环境jdk7,故没用labmda表达式。
第一种:
public Map<String, Object> getDataQx(List<ReportTableEntity> listTime,List<TSType> listsig) {
Map<String, Object> map = new HashMap<String, Object>();// 查询条件
Map<String, Object> dateMap = new HashMap<String, Object>();
Map<String, Object> dateRootMap = null;
Map<String, Object> mapinfo = null;
Map<String, Object> resultMap =null ;
List<SiteInfoSnapshotEntity> sEntities = new ArrayList<>();
for (ReportTableEntity reportTableEntity : listTime) {
dateRootMap = new HashMap<String, Object>();// 放数据
for (TSType typeEntity : listsig) {
("county", ());
("dtime", ());
sEntities = (map);
// 区县对应的数据
mapinfo = new HashMap<String, Object>();// 放每个区县的详情
("info", (0));
((), mapinfo);
}
// 日期> 区县 > 数据
((), dateRootMap);
// ----------------------------
resultMap = sortMapByKey(dateMap); //按Key进行排序
for (<String, Object> entry : ()) {
(() + " " + ());
}
// ----------------------------
}
return resultMap;
}
public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
if (map == null || ()) {
return null;
}
//利用匿名内部类,重写compare to 方法
Map<String, Object> sortMap = new TreeMap<String, Object>(new MapKeyComparator());
(map);
return sortMap;
}
public class MapKeyComparator implements Comparator<String> {
@Override
public int compare(String str1, String str2) {
return (str1);
}
}
第二种:
public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
if (map == null || ()) {
return null;
}
Map<String, Object> sortMap = new TreeMap<String, Object>(new Comparator<String>() {
@Override
public int compare(String o1,String o2) {
return ((String)o1).compareTo((String) o2);
}
});
(map);
return sortMap;
}