淘先锋技术网

首页 1 2 3 4 5 6 7

【java】Comparator的用法 :具体参考https://blog.csdn.net/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) {
				map.put("county", typeEntity.getTypename());
				map.put("dtime", reportTableEntity.getDateof());
				sEntities = siteInfoSnapshotService.getCounty(map);
				// 区县对应的数据
				mapinfo = new HashMap<String, Object>();// 放每个区县的详情
				mapinfo.put("info", sEntities.get(0));
				dateRootMap.put(typeEntity.getTypename(), mapinfo);

			}
			// 日期> 区县 > 数据
			dateMap.put(reportTableEntity.getDateof(), dateRootMap);
			// ----------------------------
			 resultMap = sortMapByKey(dateMap);  //按Key进行排序

		        for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
		            System.out.println(entry.getKey() + " " + entry.getValue());
		        }
			// ----------------------------
		}
		return resultMap;
	}
public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
		if (map == null || map.isEmpty()) {
			return null;
		}
        //利用匿名内部类,重写compare to 方法
		
		Map<String, Object> sortMap = new TreeMap<String, Object>(new MapKeyComparator());

		sortMap.putAll(map);

		return sortMap;
	}
public class MapKeyComparator implements Comparator<String> {
	

	    @Override
	    public int compare(String str1, String str2) {

	        return str2.compareTo(str1);
	    }
	}

 

第二种:

public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
		if (map == null || map.isEmpty()) {
			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);
			}
		});

		sortMap.putAll(map);

		return sortMap;
	}