javaandroidguavaandroid-guava

No SortedMultiMap in Guava?


I am trying to find a way to get a sorted multimap. I checked Guava which offers two separate collection data structures that combined could answer my problem. What's striking is that SortedSetMultimap can not contain identical keys because it's a Set while Multimap is in the same symbol. What's up with that?

EDIT

In C++, I've got something like that, which hopefully will tell you how I intend to use similar functionality in Java:

  struct KeyCompare : public binary_function<pair<double,double>, pair<double,double>, bool>
  {
    bool operator()(const pair<double,double>& p1, const pair<double,double>& p2) const;
  };

  multimap<pair<double,double>, Object*, KeyCompare> _list;

  .../...

  KeyCompare key_compare;

  while (( ! _list.empty() && key_compare(_list.begin()->first, k))) {

    u = _list.begin()->second;
    v = _list.begin()->first;

In English: I need a map with keys being pairs of doubles referencing some object contained in the value. The map can contains multiple keys that are identicals (same pair of double numbers happens), so this needs to be a multimap or bag. When this occurs, the element can be inserted in the collection and when picking the top element, it should return one of those (doesn't matter which one). I need for the collection to be mutable because for each iteration, I am picking the lesser element and removing it from the map.


Solution

  • Are you possibly looking for MultimapBuilder.treeKeys().arrayListValues().build() ?

    If you needed to pass a comparator, that might look like

     MultimapBuilder.treeKeys(new Comparator<Pair<Double, Double>>() {
          @Override public int compare(Pair<Double, Double> p1, Pair<Double, Double> p2) {
            return ComparisonChain.start()
                .compare(p1.first(), p2.first())
                .compare(p1.second(), p2.second())
                .result();
          }
        }).arrayListValues().build();