-1

So i have HashMap which i convert it to Object so i can sort it by value, now by default i sort it as descending, but i would need other option too to sort it as ascending.

I used simple array sort:

HashMap<String, Integer> prefMap = getMyList();

Object[] a = prefMap.entrySet().toArray();

Arrays.sort(a, new Comparator() {
    public int compare(Object o1, Object o2) {
        return ((Map.Entry<String, Integer>) o2).getValue()
                .compareTo(((Map.Entry<String, Integer>) o1).getValue());0
    }
});

The upper code works for descending, should i just compare with if/else if i want to sort them as ascending?

YCF_L
  • 51,266
  • 13
  • 85
  • 129
HyperX
  • 1,007
  • 2
  • 20
  • 41

2 Answers2

1

To sort ascending, you may simply call the reversed version of your Comparator :

Arrays.sort(a, new Comparator<Map.Entry<String, Integer>>() {

    public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
        return (o2).getValue().compareTo((o1).getValue());
    }

}.reversed()); // <-- see here
Arnaud
  • 16,865
  • 3
  • 28
  • 41
0

Swap o2 and o1 in compareTo, you get it ascending....

HashMap<String, Integer> prefMap = getMyList();    
Object[] a = prefMap.entrySet().toArray();   
Arrays.sort(a, new Comparator() {
    public int compare(Object o1, Object o2) {
        return ((Map.Entry<String, Integer>) o1).getValue()
                .compareTo(((Map.Entry<String, Integer>) o2).getValue());
    }
});