java的hashmap排序,如何在Java中对HashMap进行排序

How are we able to sort a HashMap?

I want to sort on the basis of a value in the ArrayList.

解决方案

Do you have to use a HashMap ? If you only need the Map Interface use a TreeMap

Ok I think now I understood your question, you want to sort by comparing values in the hashMap. You have to write code to do this, if you want to do it once you can sort the values of your hashMap:

Map people = new HashMap();

Person jim = new Person("Jim", 25);

Person scott = new Person("Scott", 28);

Person anna = new Person("Anna", 23);

people.put(jim.getName(), jim);

people.put(scott.getName(), scott);

people.put(anna.getName(), anna);

// not yet sorted

List peopleByAge = new ArrayList(people.values());

Collections.sort(peopleByAge, new Comparator() {

public int compare(Person o1, Person o2) {

return o1.getAge() - o2.getAge();

}

});

for (Person p : peopleByAge) {

System.out.println(p.getName() + "\t" + p.getAge());

}

If you want to access this sorted list often, then you should insert your elements in the hashMap AND in a sorted Set (TreeSet for example)...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值