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)...