Eyal Golan
Eyal Golan

Reputation: 804

Joiner - skipDuplicates

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

Upvotes: 3

Views: 350

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198211

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.

Upvotes: 9

Related Questions