使用Comparator根据Map的value进行排序:
在写推荐系统时,使用到余弦相似度算法对用户进行推荐,里面需要根据value值对推荐由相似度高到底排序,所以撸了一个实现Comparator对map中value进行排序的工具方法。
public static Map<String, Float> sortMapByValue(Map<String, Float> oriMap) {
if (oriMap == null || oriMap.isEmpty()) {
return null;
}
Map<String, Float> sortedMap = new LinkedHashMap<String, Float>();
List<Map.Entry<String, Float>> entryList = new ArrayList<Map.Entry<String, Float>>(
oriMap.entrySet());
Collections.sort(entryList, new MapValueComparator());
Iterator<Map.Entry<String, Float>> iter = entryList.iterator();
Map.Entry<String, Float> tmpEntry = null;
while (iter.hasNext()) {
tmpEntry = iter.next();
sortedMap.p