Question

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));
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top