【java】comparator的用法: https://www.coonote.com/java-note/java-comparator.html
这两种其实都差不多,只是匿名内部类的不同写法而已。项目环境jdk7,故没用labmda表达式。
第一种:
public map getdataqx(list listtime,list listsig) {
map map = new hashmap();// 查询条件
map datemap = new hashmap();
map daterootmap = null;
map mapinfo = null;
map resultmap =null ;
list sentities = new arraylist<>();
for (reporttableentity reporttableentity : listtime) {
daterootmap = new hashmap();// 放数据
for (tstype typeentity : listsig) {
map.put("county", typeentity.gettypename());
map.put("dtime", reporttableentity.getdateof());
sentities = siteinfosnapshotservice.getcounty(map);
// 区县对应的数据
mapinfo = new hashmap();// 放每个区县的详情
mapinfo.put("info", sentities.get(0));
daterootmap.put(typeentity.gettypename(), mapinfo);
}
// 日期> 区县 > 数据
datemap.put(reporttableentity.getdateof(), daterootmap);
// ----------------------------
resultmap = sortmapbykey(datemap); //按key进行排序
for (map.entry entry : resultmap.entryset()) {
system.out.println(entry.getkey() " " entry.getvalue());
}
// ----------------------------
}
return resultmap;
}
public static map sortmapbykey(map map) {
if (map == null || map.isempty()) {
return null;
}
//利用匿名内部类,重写compare to 方法
map sortmap = new treemap(new mapkeycomparator());
sortmap.putall(map);
return sortmap;
}
public class mapkeycomparator implements comparator {
@override
public int compare(string str1, string str2) {
return str2.compareto(str1);
}
}
第二种:
public static map sortmapbykey(map map) {
if (map == null || map.isempty()) {
return null;
}
map sortmap = new treemap(new comparator() {
@override
public int compare(string o1,string o2) {
return ((string)o1).compareto((string) o2);
}
});
sortmap.putall(map);
return sortmap;
}