-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?

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
HyperX
  • 1,121
  • 2
  • 22
  • 42

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
  • 17,229
  • 3
  • 31
  • 44
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());
    }
});
Ying Cherry
  • 143
  • 1
  • 5