Alex Dmitriev
Alex Dmitriev

Reputation: 3710

Multiset intersection-like operation in Java

Given two multisets, for example, the first one:

Green
Green
Blue
Yellow
Yellow
Yellow
Cyan
Cyan

And the second one:

Green
Yellow
Yellow
Magenta
Black
Black

I need to get their intersection so that the result would look like:

Green
Green
Green
Yellow
Yellow
Yellow
Yellow
Yellow

What is the efficient way to achieve this in Java? (Any link to a library or function would be appreciated.)

Upvotes: 0

Views: 762

Answers (3)

ColinD
ColinD

Reputation: 110054

It looks like you want the sum of the multisets, filtered to include only the elements that appear at least once in their intersection. Here's one way you could get the result you're looking for in Guava:

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]

Upvotes: 5

Leo Nomdedeu
Leo Nomdedeu

Reputation: 338

Given your Multiset is a descendant of Set, you can retainAll from one to the other and the other way around, and then combine both subsets like this:

multiset1.retainAll(multiset2);
multiset2.retainAll(multiset1);
multiset1.addAll(multiset2);

If I understool your question correctly you will end up with what you want in multiset1, although you may need to sort it. The cardinality should be correct doing it that way.

Upvotes: 1

Alexey Malev
Alexey Malev

Reputation: 6533

You may want to try Guava Multiset, which has similar API to normal Java Set, including retain operations you may be interested in.

Also please be advised that questions asking to recommend a tool/library are typically considered offtopic on SO because the answers are really subjective.

Upvotes: 1

Related Questions