有时候会在对接参数时会对参数的排序有要求.这里就需要研究Map的排序机制
1.hashMap是无序的
2.treeMap则是有序的
1).如果不指定排序器则默认按照key来排序:
public static void main(String[] args) {
Map<Integer, Student> stuMap = new TreeMap<Integer, Student>();
Student s1 = new Student(20, "小三", 18);
Student s2 = new Student(10, "小四", 18);
Student s3 = new Student(12, "小五", 18);
Student s4 = new Student(51, "小六", 18);
Student s5 = new Student(1, "小七", 18);
stuMap.put(s1.getId(), s1);
stuMap.put(s2.getId(), s2);
stuMap.put(s3.getId(), s3);
stuMap.put(s4.getId(), s4);
stuMap.put(s5.getId(), s5);
for (Student stu : stuMap.values()) {
System.out.println(stu.getId() + " " + stu.getName());
}
}
输出结果1 小七
10 小四
12 小五
20 小三
51 小六
2).如果指定了排序器则按照排序器来排序
public static void main(String[] args) {
//指定排序器
TreeMap<String, String> treeMap2 = new TreeMap<String, String>(new Comparator<String>(){
/*
* int compare(Object o1, Object o2) 返回一个基本类型的整型,
* 返回负数表示:o1 小于o2,
* 返回0 表示:o1和o2相等,
* 返回正数表示:o1大于o2。
*/
public int compare(String o1, String o2) {
//指定排序器按照降序排列
return o2.compareTo(o1);
}
});
treeMap2.put("2", "1");
treeMap2.put("b", "1");
treeMap2.put("1", "1");
treeMap2.put("a", "1");
System.out.println("treeMap2="+treeMap2);
}
输出结果treeMap2={b=1, a=1, 2=1, 1=1}