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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With