java 实现对HashMap
的 key/value
进行排序
1. 代码
package test;
import java.util.*;
public class MapTest {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("d", 2);
map.put("c", 1);
map.put("b", 4);
map.put("a", 3);
List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(map.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 + " ");
}
}
}
2. 执行结果
3. 案例
在以上代码的基础上,如果要实现以下需求:
对Map的value进行排序,如果value相同,那么则按照key进行排序。
import java.util.*;
public class Main {
private static Map<String, Integer> student = new HashMap<String, Integer>();
private static List<Map.Entry<String, Integer>> lists ;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int totalNumber = in.nextInt();
int lineNumber = in.nextInt();
System.out.println("total Number = " + totalNumber + ", lineNumber = " + lineNumber);
in.nextLine();
String line[];
String name;
int height;
for (int i = 0; i < totalNumber; i++) {
line = in.nextLine().trim().split(" ");
name = line[0];
height = Integer.parseInt(line[1]);
System.out.println("name = " + name + ", height = " + height);
student.put(name, height);
}
System.out.println("student.size = " + student.size());
lists = new ArrayList<Map.Entry<String, Integer>>(student.entrySet());
sort();
for(int i = 0;i < lists.size();i++) {
System.out.println(lists.get(i));
}
}
//根据height and name 排序
public static void sort() {
Collections.sort(lists, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
int status = o1.getValue().compareTo(o2.getValue()) ;
if (status == 0) {
status = o1.getKey().compareTo(o2.getKey());
}
return status;
}
});
}
}
执行结果如下: