Home > GWT > Sort hash map keys in revert order in GWT

Sort hash map keys in revert order in GWT

This short post will be about sorting. In GWT, unfortunately, there are no descending iterator. Eclipse allow you to add it, but on compile time it just crashed. Solution is simple but not obvious, so I decided to post about this.

Task: Sort hash map with some keys in descending order. For simplicity we will take an integer keys.

Solution:

Let’s assume we have a hashMapForSort – as hash map that we need to sort. Following code below will return all your keys in descending order

List<Integer> tmp = new ArrayList<Integer>(hashMapForSort.keySet());
 
Collections.sort(tmp, new Comparator<Integer>() {
 
    @Override
    public int compare(Integer arg0, Integer arg1) {
        return -arg0.compareTo(arg1); // a little trick to have numbers in descending order
    }
 
});
 
Iterator<Integer> iter = tmp.iterator(); // create an iterator by sorted collection
while (iter.hasNext()) {
    Log.warn(iter.next() + "");
}

Actually, you can sort any objects in this way, just defining a comparator you need.

Categories: GWT Tags: ,
  1. No comments yet.
  1. No trackbacks yet.