2

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);
Tunaki
  • 132,869
  • 46
  • 340
  • 423
izengod
  • 1,116
  • 5
  • 17
  • 41
  • 1
    [How to sort TreeMap](http://stackoverflow.com/a/18923308/5168011) – Guy Jan 31 '16 at 13:35
  • Do you always need them in this order or sometimes in reverse sometimes not ? – Dici Jan 31 '16 at 13:39
  • 1
    Possible duplicate of [Sorting Descending order: Java Map](http://stackoverflow.com/questions/18923167/sorting-descending-order-java-map) – RHA Jan 31 '16 at 13:40
  • 1
    @guy and RHA : this is a `Multimap` from Guava, not a regular Java `Map` – Dici Jan 31 '16 at 13:43
  • @Dici What about [this](http://stackoverflow.com/questions/10589716/how-to-sort-guava-multimap-key-date)? or [this](http://stackoverflow.com/questions/7881629/sort-guava-multimap-by-number-of-values) ? – Guy Jan 31 '16 at 13:45
  • @Dici : exactly! This is Guava multimap. Is there any other MultiMap type rather than TreeMultimap that can do this ? – izengod Jan 31 '16 at 13:46
  • @guy Yep, those ones are ok. Answered by the guy who wrote those classes :) Even better – Dici Jan 31 '16 at 13:53

2 Answers2

8

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]}.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
0

This is what I´ve found what is actually working for me

  SortedSetMultimap<String, String> multiMap = TreeMultimap.create(
                Comparator.reverseOrder(), // Key sorting
                (o1, o2) -> 0              // Value sorting
        );
Marian Klühspies
  • 15,824
  • 16
  • 93
  • 136