Search code examples
javacollectionsmapsguavamultimap

Sort a TreeMultimap in descending (reversed) order


The output is: Top pincodes: {1=[456008, 456600, 456666], 2=[560089], 4=[456098, 567789]}

I want them to be in this order: {4=[456098,567789], 2=[560089], 1=[456008, 456600, 456666]}

HashMap<Integer, Integer> totalCustomersByPin = new HashMap<Integer, Integer>();
TreeMultimap<Integer, Integer> totalDeliveriesToPin = TreeMultimap.create();
Iterator<Entry<Integer, Integer>> iterator = totalCustomersByPin.entrySet().iterator();

while (iterator.hasNext()) {
    Entry<Integer, Integer> pair = iterator.next();
    totalDeliveriesToPin.put(pair.getValue(), pair.getKey());
}
System.out.println("Top pincodes:" + totalDeliveriesToPin);

Solution

  • You can set a key comparator when creating the TreeMultimap. You can use Ordering.natural() and then call reverse() to sort the key in the reverse order of their natural ordering.

    Sample code:

    public static void main(String[] args) {
        TreeMultimap<Integer, Integer> map = TreeMultimap.create(Ordering.natural().reverse(), Ordering.natural());
        map.put(1, 456008);
        map.put(1, 456600);
        map.put(1, 456666);
        map.put(2, 560089);
        map.put(4, 456098);
        map.put(4, 567789);
        System.out.println(map);
    }
    

    This will print: {4=[456098, 567789], 2=[560089], 1=[456008, 456600, 456666]}.