Having a Multimap sorted on keys only in Java

后端 未结 8 1236
北荒
北荒 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:43

    How about this:

        public static Multimap<Integer, MyObject> indexOnScore(Iterable<MyObject> i) {
            Multimap<Integer, MyObject> m = Multimaps.index(i, myObjectToScore());
    
            Multimap<Integer, MyObject> sortedKeys = Multimaps.newMultimap(
                    Maps.<Integer, Collection<MyObject>>newTreeMap(),
                    new Supplier<Collection<MyObject>>() {
                        @Override
                        public Collection<MyObject> get() {
                            return Lists.newArrayList(); // Or a Set if appropriate
                        }
                    }
            );
    
            sortedKeys.putAll(m);
    
            return sortedKeys;
        }
    

    There would be the overhead of creating two separate Multimaps in this case, though.

    0 讨论(0)
  • 2020-12-03 17:47

    You can do it with TreeMultimap if you use Comparators.

    Create a Comparator for the key type and the value type (MyObject?). Then use create(Comparator keyComparator, Comparator valueComparator) to make the map.

    The benefit of using a Comparator over implementing Comparable is that you can make the Comparator specific to the situation that you want with the map and it doesn't effect your object in general. As long as your Comparator is consistent with equals it can do whatever you want.

    0 讨论(0)
提交回复
热议问题