Having a Multimap sorted on keys only in Java

后端 未结 8 1246
北荒
北荒 2020-12-03 17:19

I would like to have a c.g.c.c.Multimap that is sorted based on keys only. The values shouldn\'t be sorted. I\'ve tried to build something with guava\'s T

8条回答
  •  暖寄归人
    2020-12-03 17:23

    Best solution which always works for me is to use Multimap & TreeMultiMap. this will order results in ascending order on keys even if you have multiple duplicate keys. Solution below:

    Multimap map= TreeMultimap.create(Ordering.natural().reverse(),         Ordering.natural());
    
    if (!map.isEmpty()) {               
                    printMap(map);
                }
    
    public static  void printMap(Multimap map) throws Exception {
            for (Map.Entry entry : map.entries()) {
                System.out.println("Key : " + entry.getKey() 
                    + " Value : " + entry.getValue());              
            }
        }
    

提交回复
热议问题