假设有这样的类:
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<String> mapKeys =
new
TreeSet<>(map.keySet());
这个时候要POJO重写hashcode和equals方法:
4) JAVA8的方法:
根据KEY排序:
Map<Integer, Student> sortedMap = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors
.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new))
也可以根据MAP的值来排序
sortedMap = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors
.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new));
也可以使用Collections.reverseOrder方法,逆序排序:
sortedMapDesc = map.entrySet()
.stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByKey()))
.collect(Collectors
.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new));
则出来的值为倒序:
{1005=[id=1005, name=Joseph], 1004=[id=1004, name=Peter],
1003=[id=1003, name=Sam], 1002=[id=1002, name=Miranda],
1001=[id=1001, name=Kate]}