1

Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?

Dear, i have an hash map, in which i have saved tho values: singer(string) and popularity(integer).

Now, i want order this hash map according the popularity.

How can do it in java?

Community
  • 1
  • 1
Francesco Nigro
  • 479
  • 2
  • 8
  • 20

3 Answers3

2

HashMaps can (by design) not be ordered. If you need an ordered map, use the TreeMap.

nfechner
  • 17,295
  • 7
  • 45
  • 64
2

I assume you store the singer as a key, and the popularity (of the singer) as value. A HashMap is not ordered, and a TreeMap is ordered by key, not by value, so it won't help.

If you need your singers ordered by popularity, then build a list with all the singers in the map, and then sort this list using a comparator which compares the popularity of both singers:

List<String> singers = new ArrayList<String>(map.keySet());
Collections.sort(singers, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        Integer popularity1 = map.get(s1);
        Integer popularity2 = map.get(s2);
        return popularity1.compareTo(popularity2);
    }
});
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

You cannot control the order of HashMap elements. Make a new TreeMap<Integer,List<String>> and copy your data to it. Use List<String> to cover the cases where you have duplicate int values.

Erik
  • 88,732
  • 13
  • 198
  • 189