# 如何对HashMap进行排序

15 篇文章 1 订阅

## 如何对HashMap进行排序

@Data
@AllArgsConstructor
class Student{
private Integer id;
private String name;

@Override
public String toString() {
return "{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
HashMap<Integer,Student> map=new HashMap<>();

@BeforeMethod
public void constructHashMap(){
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

1. 通过构造函数来创建

@Test
public void useTreeMap1() {
TreeMap<Integer, Student> sortedMap = new TreeMap<>(map);
System.out.println(sortedMap);
}


2. 调用putAll()方法

@Test
public void useTreeMap2() {
TreeMap<Integer, Student> sortedMap = new TreeMap<>();
sortedMap.putAll(map);
System.out.println(sortedMap);
}


{1001={id=1001, name='Kate'}, 1002={id=1002, name='Miranda'}, 1003={id=1003, name='Sam'}, 1004={id=1004, name='Peter'}, 1005={id=1005, name='Joseph'}}


### 2. 通过ArrayList

@Test
public void useArrayList() {
List<Integer> mapKeys = new ArrayList<>(map.keySet());
Collections.sort(mapKeys);
System.out.println(mapKeys);

List<Student> mapValues = new ArrayList<>(map.values());
Collections.sort(mapValues, (s1, s2) -> s1.id.compareTo(s2.id));
System.out.println(mapValues);
}


### 3. 通过TreeSet

@Test
public void useTreeSet() {
TreeSet<Integer> mapKeys = new TreeSet<>(map.keySet());
System.out.println(mapKeys);
}


### 4. 通过Java8的Streams

Map<Integer, Student> sortedMap = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors
.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,


Map<Integer, Student> sortedMap = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors
.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,


 Map<Integer,Student> sortMapDesc= map.entrySet()
.stream()
.sorted(Collections
.reverseOrder(Map.Entry.comparingByKey()))
.collect(Collectors


11-11
05-14 1万+
08-06 328
09-17 9669
06-07 2133
08-21 185
01-08 568
09-11 219

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。