Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joiner - skipDuplicates

Tags:

guava

I have a situation where I want to remove duplicates from a collection (list) and then join them. I wanted to make an extension for Joiner, but it is impossible as all constructors are private.

Here's a code snippet of what we did:

Collection<String> tokens = newArrayList();
for (int i = 0; i < numOfFoundTitles; i++) {
    if (!tokens.contains(titlesInRange.get(i).titleAsTokens)) {
        tokens.add(titlesInRange.get(i).getTitleAsTokens());
    }
}
return titleTokensJoiner.join(tokens);

Any suggestions? I thought about Function / Predicate, but they are not suitable there.

Thanks

Eyal

like image 906
Eyal Golan Avatar asked Aug 07 '26 09:08

Eyal Golan


1 Answers

return titleTokensJoiner.join(ImmutableSet.copyOf(tokens));

Short, sweet, and correct. ImmutableSet preserves the order of the original input, but ignores repeated occurrences of an element after the first occurrence.

like image 149
Louis Wasserman Avatar answered Aug 12 '26 01:08

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!