问题
我们怎样才能对aHashMap<key, ArrayList>
进行排序?
我想根据ArrayList
中的值进行排序。
#1 热门回答(121 赞)
你必须使用HashMap吗?如果你只需要Map Interface,请使用aTreeMap
好吧我想现在我理解你的问题,你想通过比较hashMap中的值来排序。如果要在对hashMap的值进行排序后执行此操作,则必须编写代码来执行此操作:
Map<String, Person> people = new HashMap<String, Person>();
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<Person> peopleByAge = new ArrayList<Person>(people.values());
Collections.sort(peopleByAge, new Comparator<Person>() {
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
});
for (Person p : peopleByAge) {
System.out.println(p.getName() + "\t" + p.getAge());
}
如果你想经常访问这个排序列表,那么你应该在hashMapAND中插入一个有序的Set(例如TreeSet)......
#2 热门回答(32 赞)
按hasmap键排序列表:
SortedSet<String> keys = new TreeSet<String>(myHashMap.keySet());
按散列映射值排序列表:
SortedSet<String> values = new TreeSet<String>(myHashMap.values());
如果是重复的 Map 值:
List<String> mapValues = new ArrayList<String>(myHashMap.values());
Collections.sort(mapValues);
祝你好运!
#3 热门回答(23 赞)
http://snipplr.com/view/2789/sorting-map-keys-by-comparing-its-values/
得到钥匙
List keys = new ArrayList(yourMap.keySet());
排序他们
Collections.sort(keys)
打印它们。
在任何情况下,你都不能在HashMap中排序值(根据APIThis class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time
)。
虽然你可以将所有这些值推送到LinkedHashMap
,但以后也可以使用。