how we will be able to sort a hashmap
i want so sort in the basis of a value in array list... thanx in advance..............
how we will be able to sort a hashmap
i want so sort in the basis of a value in array list... thanx in advance..............
Without any more information, it's hard to know exactly what you want. However, when choosing what data structure to use, you need to take into account what you need it for. Hashmaps are not designed for sorting - they are designed for easy retrieval. So in your case, you'd probably have to extract each element from the hashmap, and put them into a data structure more conducive to sorting, such as a heap or a set, and then sort them there.
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)...
Seems like you might want a treemap.
http://java.sun.com/j2se/1.4.2/docs/api/java/util/TreeMap.html
You can pass in a custom comparator to it if that applies.
If you want to combine a Map for efficient retrieval with a SortedMap, you may use the ConcurrentSkipListMap.
Of course, you need the key to be the value used for sorting.
http://snipplr.com/view/2789/sorting-map-keys-by-comparing-its-values/
get the keys
List keys = new ArrayList(yourMap.keySet());
Sort them
Collections.sort
print them.
In any case, you can't have sorted values in HashMap [ Acc to API 'This 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' ].
Though you can push all these sorted value to LinkedhashMap, for later use as well.