我正在尝试将两个合并或“总和”合二为一SortedMultiset
。但是,在Multisets
类中,没有这样的方法。我想做类似的事情:
// 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);
但这会导致:
java: incompatible types
required: com.google.common.collect.SortedMultiset<java.lang.Integer>
found: com.google.common.collect.Multiset<java.lang.Integer>
我可以通过更改两组的类型来做到这一点,如下所示:
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());
我想知道是否有一种方法可以更优雅地实现这一点,最重要的是通过SortedMultiset
像第一个示例中那样直接使用实例。
编辑:
我缺少的部分是这一行:
SortedMultiset<Integer> sum = Multisets.sum(set1, set2);
应该:
SortedMultiset<Integer> sortedSum = ImmutableSortedMultiset.copyOf(Multisets.sum(set1, set2));