1、hashmap的value排序
//hashMap value 排序
public class demo3 {
public static void main(String[] args) {
HashMap map_Data = new HashMap();
map_Data.put("0", 90);
map_Data.put("1", 50);
map_Data.put("2", 50);
map_Data.put("3", 25);
map_Data.put("4", 85);
map_Data.put("5", 95);
map_Data.put("6", 8);
map_Data.put("7", 10);
map_Data.put("9",2);
System.out.println(map_Data);
//map 按照value排序
List<Map.Entry<String, Integer>> list_Data = new ArrayList<Map.Entry<String, Integer>>(map_Data.entrySet());
Collections.sort(list_Data, (o1, o2) -> {
if (o2.getValue() != null && o1.getValue() != null && o2.getValue().compareTo(o1.getValue()) > 0) {
return 1;
} else {
return -1;
}
});
System.out.println(list_Data);
}
}
结果:
如果Value是String 类型(数字)的转成Int类型再排序
2.String类型比较:
public static void main(String[] args) {
HashMap map_Data = new HashMap();
map_Data.put("0", "90");
map_Data.put("1", "50");
map_Data.put("2", "50");
map_Data.put("3", "25");
map_Data.put("4", "85");
map_Data.put("5", "95");
map_Data.put("6", "8");
map_Data.put("7", "10");
map_Data.put("9","12");
System.out.println(map_Data);
//map 按照value排序
List<Map.Entry<String, String>> list_Data = new ArrayList<Map.Entry<String, String>>(map_Data.entrySet());
Collections.sort(list_Data, new Comparator<Map.Entry<String, String>>() {
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
if (o2.getValue() != null && o1.getValue() != null && o2.getValue().compareTo(o1.getValue()) > 0) {
return 1;
} else {
return -1;
}
}
});
System.out.println(list_Data);
}
结果:
{0=90, 1=50, 2=50, 3=25, 4=85, 5=95, 6=8, 7=10, 9=12}
[5=95, 0=90, 4=85, 6=8, 2=50, 1=50, 3=25, 9=12, 7=10]
结果明显不是我们想要的,看看源码:
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2); //取最小的那个
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
源码中的String比较是取长度,然后获取长度最短的(Math.min(len1, len2)),然后进行字符比较code值