0

I am trying to merge, or "sum", two SortedMultiset into one. However, in the Multisets class, there is no such method. I would like to do something like:

// this is just an example, the actual sets would be created differently (they are NOT empty!)
SortedMultiset<Integer> set1 = ImmutableSortedMultiset.of();
SortedMultiset<Integer> set2 = ImmutableSortedMultiset.of();
SortedMultiset<Integer> sum = Multisets.sum(set1, set2);

but this causes:

java: incompatible types
required: com.google.common.collect.SortedMultiset<java.lang.Integer>
found:    com.google.common.collect.Multiset<java.lang.Integer>

I can do this by changing the type of the two sets as in:

Multiset<Integer> set1 = // create the first one...
Multiset<Integer> set2 = // create the second one...
Multiset<Integer> sum = Multisets.sum(set1,set2); // does NOT work
SortedMultiset<Integer> sortedSum = ImmutableSortedMultiset.copyOf(sum.iterator());

I was wondering if there was a way to achieve this more elegantly and most of all by using SortedMultiset instances directly as in the first example.

EDIT:

The part I was missing was that this line:

SortedMultiset<Integer> sum = Multisets.sum(set1, set2);

Should be:

SortedMultiset<Integer> sortedSum = ImmutableSortedMultiset.copyOf(Multisets.sum(set1, set2));
Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94

1 Answers1

2

Louis is absolutely right, Multisets.sum(set1, set2) certainly does work, nor does copying to an ImmutableSortedMultiset cause any trouble.

public static void main(String[] args) {

    final SortedMultiset<Integer> set1 = ImmutableSortedMultiset.of(1, 2, 2, 3, 3, 3);
    final SortedMultiset<Integer> set2 = ImmutableSortedMultiset.of(1, 1, 2, 4);
    final SortedMultiset<Integer> sum = ImmutableSortedMultiset.copyOf(Multisets.sum(set1, set2));
    System.out.println(sum);
}

outputs:

[1 x 3, 2 x 3, 3 x 3, 4]

I suspect that it is the piece you have redacted, and replaced with ImmutableSortedMultiset.of(); that is giving you trouble. But I cannot comment too much there as you've neglected to share it.

Ray
  • 4,829
  • 4
  • 28
  • 55
  • Your code is different than mine. I haven't spotted the problem before but it's clear: `Multisets.sum()` returns a `Multiset`, not a `SortedMultiset`, hence copying in the `SortedMultiset` does the trick. So there is no omission on my part. I guess my assumption was that it would be possible to __avoid__ the copy all together. – Giovanni Botta Mar 13 '14 at 20:15
  • Note that simply calling `Multisets.sum()` does _not_ return a _sorted_ `Multiset`: if you swap the arguments and do `Multisets.sum(set2, set1)`, you get `[1 x 3, 2 x 3, 4, 3 x 3]`. – Frank Pavageau Mar 14 '14 at 09:07