【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;
}