1.value值为基本类型:
public static Map<String, Long> sortByValue(Map<String, Long> map) {
List<Map.Entry<String, Long>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Long>>() {
public int compare(Map.Entry<String, Long> o1, Map.Entry<String, Long> o2) {
Long result = o2.getValue() - o1.getValue();
if (result > 0)
return 1;
else if (result == 0)
return 0;
else
return -1;
}
});
Map<String, Long> result = new LinkedHashMap<>();
int i = 1;
for (Map.Entry<String, Long> entry : list) {
result.put(entry.getKey(), entry.getValue());
System.err.println("第" + i + "名对应的groupId为" + entry.getKey() + ",对应的值为" + entry.getValue());
i++;
}
return result;
}
2.value值为数组类型(依次排序数组对应的元素);
public static Map<String, Long> sortByArrayValue(Map<String, long[]> map) {
Map<String, Long> map2 = new HashMap<String, Long>();
Map<String, Long> result = new LinkedHashMap<>();
// 将i时刻的值存入新的map2,并排序输出到一个数组中
for (int i = 0; i < 24; i++) {
for (String key : map.keySet()) // 循环便利map
{
map2.put(key, map.get(key)[i]);
}
List<Map.Entry<String, Long>> list = new LinkedList<>(map2.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Long>>() {
public int compare(Map.Entry<String, Long> o1, Map.Entry<String, Long> o2) {
Long result = o2.getValue() - o1.getValue();
if (result > 0)
return 1;
else if (result == 0)
return 0;
else
return -1;
}
});
int j = 1;
for (Map.Entry<String, Long> entry : list) {
result.put(entry.getKey(), entry.getValue());
System.err
.println("第" + i + "时刻,第" + j + "名对应的groupId为" + entry.getKey() + ",对应的值为" + entry.getValue());
j++;
}
System.out.println();
}
return result;
}
参照:
1.http://blog.sina.com.cn/s/blog_8e6f1b330101h7fa.html
2.http://www.cnblogs.com/liu-qing/p/3983496.html 通用升序
3.http://blog.youkuaiyun.com/tsingheng/article/details/7909861 实例升序
4.http://www.linuxidc.com/Linux/2013-11/92867.htm 降序