HashMap排序方法
假设有这样的类
代码如下(示例):
class Student {
private Integer id;
private String name;
Student(Integer id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return "[id="+id + ", name=" + name + "]";
}
}
HashMap<Integer, Student> map = new HashMap<>();
map.put(1003, new Student(1003, "Sam"));
map.put(1005, new Student(1005, "Joseph"));
map.put(1001, new Student(1001, "Kate"));
map.put(1002, new Student(1002, "Miranda"));
map.put(1004, new Student(1004, "Peter"));
要进行排序,使用的方法有:
1) 使用TreeMap,这个方法最简单了:
TreeMap<Integer, Student> sortedMap = new TreeMap<>(map);
把MAP传进去TREEMAP中就可以了。
2) 如果仅仅是排序MAP中的KEY和VALUE,则可以:
List<Integer> mapKeys = new ArrayList<>(map.keySet());
Collections.sort(mapKeys);
List<Student> mapValues = new ArrayList<>(map.values());
Collections.sort(mapValues);
但前提是必须POJO实现Comparable接口
public class Student implements Comparable<Student> {
...
public int compareTo(Student other) {
return this.id.compareTo(other.id);
}
}
3)如果不希望排序的MAP中有KEY,的值的重复,可以用sortedset
SortedSet mapKeys = new TreeSet<>(map.keySet());
这个时候要POJO重写hashcode和equals方法: