给定两个多集,例如,第一个:

Green
Green
Blue
Yellow
Yellow
Yellow
Cyan
Cyan

第二个是:
Green
Yellow
Yellow
Magenta
Black
Black

我需要得到他们的交集,这样结果会像:
Green
Green
Green
Yellow
Yellow
Yellow
Yellow
Yellow

在java中实现这一点的有效方法是什么?
(欢迎链接到库或函数。)

最佳答案

看起来您希望筛选的多集的sum只包含在其交叉点中至少出现一次的元素有一种方法可以让你在番石榴中得到你想要的结果:

ImmutableMultiset<String> first = ImmutableMultiset.of(
    "Green", "Green",
    "Blue",
    "Yellow", "Yellow", "Yellow",
    "Cyan", "Cyan");
ImmutableMultiset<String> second = ImmutableMultiset.of(
    "Green",
    "Yellow", "Yellow",
    "Magenta",
    "Black", "Black");

Multiset<String> result = Multisets.filter(
    Multisets.sum(first, second),
    Predicates.in(Multisets.intersection(first, second)));

System.out.println(result);  // [Green x 3, Yellow x 5]

10-02 10:08