[英]Guava ImmutableSortedMultiset: how to “sum” two instances?
I am trying to merge, or "sum", two SortedMultiset
into one. 我正在尝试将两个
SortedMultiset
合并或“求和”为一个。 However, in the Multisets
class, there is no such method. 但是,在
Multisets
类中,没有这样的方法。 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. 我想知道是否有一种方法可以像第一个示例中那样直接使用
SortedMultiset
实例来更优雅地实现此目的,而最重要的是。
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));
Louis is absolutely right, Multisets.sum(set1, set2)
certainly does work, nor does copying to an ImmutableSortedMultiset
cause any trouble. Louis绝对正确,
Multisets.sum(set1, set2)
当然可以工作,复制到ImmutableSortedMultiset
也不会造成任何麻烦。
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();
我怀疑这是您已编辑的部分,并已替换为
ImmutableSortedMultiset.of();
that is giving you trouble. 那给你带来麻烦。 But I cannot comment too much there as you've neglected to share it.
但是我不能在这里发表过多评论,因为您忽略了分享它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.