如何在Java中对HashMap进行排序 [英] How to sort a HashMap in Java
问题描述
如何排序 HashMap< key,ArrayList>
?
我想排序在 ArrayList
中的值的基础。
使用HashMap?如果您只需要Map Interface,请使用 TreeMap
好吧,我想现在我明白了你的问题,你想通过比较hashMap 。您必须编写代码才能执行此操作,如果您希望在对hashMap的值进行排序时执行此操作:
Map< ; String,Person> people = new HashMap< String,Person>();
Person jim = new Person(Jim,25);
Person斯科特=新人(Scott,28);
人anna =新人(Anna,23);
people.put(jim.getName(),jim);
people.put(scott.getName(),scott);
people.put(anna.getName(),anna);
//尚未排序
列表< Person> peopleByAge = new ArrayList< Person>(people.values());
Collections.sort(peopleByAge,new Comparator< Person>(){
$ b $ public int compare(Person o1,Person o2){
return o1.getAge( ) - o2.getAge();
}
}); (Person p:peopleByAge){
System.out.println(p.getName()+\ t+ p.getAge());
$ b 如果你想经常访问这个排序列表,那么你应该插入你的元素在有序集合(例如TreeSet)中的hashMap AND ...
How are we able to sort a HashMap<key, ArrayList>
?
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<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());
}
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)...
这篇关于如何在Java中对HashMap进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!