题目:
将Hashmap<string,integer>中的key输出到list中,并且按对应的value从大到小排序
* 例如: {‘A’:2,‘B’:3,‘C’:1}的hashmap输出{‘C’,‘A’,‘B’}
package com.example.mybtaispuls.test;
import java.util.*;
/**
* @program: test
* @description:
* @author: liulq
*/
public class Test1 {
/**
* 将Hashmap<string,integer>中的key输出到list中,并且按对应的value从大到小排序
* 例如: {'A':2,'B':3,'C':1}的hashmap输出{'C','A','B'}
* @param args
*/
public static void main(String[] args) {
Map<String, Integer> HashMap = new HashMap<String, Integer>();
HashMap.put("A", 2);
HashMap.put("B", 4);
HashMap.put("C", 1);
HashMap.put("D", 3);
List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(HashMap.entrySet());
//对HashMap中的key 进行排序
Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1,
Map.Entry<String, Integer> o2) {
return (o1.getKey()).toString().compareTo(o2.getKey().toString());
}
});
// 对HashMap中的key 进行排序后 显示排序结果
// 注意这里输出的是List 的对象 infoIds
for (int i = 0; i < infoIds.size(); i++) {
String id = infoIds.get(i).toString();
System.out.print(id + " ");
}
System.out.println();
// 对HashMap中的 value 进行排序
Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1,
Map.Entry<String, Integer> o2) {
return (o1.getValue()).toString().compareTo(o2.getValue().toString());
}
});
// 对HashMap中的 value 进行排序后 显示排序结果
for (int i = 0; i < infoIds.size(); i++) {
String id = infoIds.get(i).toString();
System.out.print(id + " ");
}
}
}
- 效果: