Skip to main content
2 of 2
improved formatting
Quill
  • 11.9k
  • 5
  • 40
  • 93

Set.add(...) has side effects by nature, which means that your filter method isn't "pure". In the given example, I don't see a concrete downside, but if you later wanted to make the stream parallel, you'd need to use a concurrent Set.

For comparison, here's a side-effect free solution using Guava's Multiset:

public static Set<String> findDuplicateWordsInText(String text) {
  Multiset<String> wordMultiset =
      ImmutableMultiset.copyOf(Splitter.on(' ').split(text));
  return wordMultiset.entrySet()
      .stream()
      .filter(entry -> entry.getCount() > 1)
      .map(Multiset.Entry::getElement)
      .collect(Collectors.toSet());
}

It probably doesn't perform as well, but the intent should (hopefully) come across clearly.