Hashmap排序的几个方法

本文介绍了如何对HashMap进行排序,包括使用TreeMap进行整体排序,以及分别对键和值进行排序。针对键值对的排序,文章提到需要实现Comparable接口。另外,文章还提及了使用SortedSet来避免键值重复的情况,此时需要重写hashCode和equals方法。

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方法:

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值