HashMap 根据key或者value排序
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<>();
map.put("aaa",1);
map.put("ddd",16);
map.put("eee",9);
map.put("bbb",3);
map.put("ccc",27);
System.out.println("通过map.entrySet()来遍历Map......");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("key:" + entry.getKey() + ", value:" + entry.getValue());
}
//HashMap 根据key排序
//获取map中的key
Set<String> keySet = map.keySet();
//将key转化为数组
Object[] array = keySet.toArray();
//再通过Arrays.sort()排序
Arrays.sort(array);
for (Object o : array) {
System.out.println(o);
}
//HashMap 根据value排序
//将HashMap转换为list进行排序
//通过Collections.sort排序
ArrayList<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
//按照value升序排序
//return o1.getValue().compareTo(o2.getValue());
//return o2.getValue()-o1.getValue();
//按照value降序排序
return o2.getValue()-o1.getValue();
}
});
//使用list.sort排序
list.sort(new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
System.out.println("HashMap排序......");
for (Map.Entry<String, Integer> entry : list) {
System.out.println("key:" + entry.getKey() + ", value:" + entry.getValue());
}
}