# Java HashMap两种简便排序方法解析

HashMap的储存是没有顺序的,而是按照key的HashCode实现.

key=手机品牌,value=价格,这里以这个例子实现按名称排序和按价格排序.

```Map phone=new HashMap();
phone.put("Apple",8899);
phone.put("SAMSUNG",7000);
phone.put("Meizu",2698);
phone.put("Xiaomi",1800);
System.out.println(phone);```

1. 按key排序

```Set set=phone.keySet();
Object[] arr=set.toArray();
Arrays.sort(arr);
for(Object key:arr){
System.out.println(key);
}```

```    for(Object key:arr){
System.out.println(key+": "+phone.get(key));
}```

2.按value排序

` List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(phone.entrySet()); //转换为list`

```list.sort(new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});```

```Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});```

```//for循环
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getKey() + ": " + list.get(i).getValue());
}
//for-each循环
for (Map.Entry<String, Integer> mapping : list){
System.out.println(mapping.getKey()+": "+mapping.getValue());
}```

```//for
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getKey() + ": " +list.get(i).getValue());
}
System.out.println();
//for-each
for (Map.Entry<String, Integer> mapping : list) {
System.out.println(mapping.getKey() + ": " +mapping.getValue());
}```