you can use regex to do this for you. sample code:
String regex = "\\b(\\w+)\\b\\s*(?=.*\\b\\1\\b)"; input = input.replaceAll(regex,""); \bMatches a word boundary position between a word character and non-word character or position (start / end of string).\wMatches any word character (alphanumeric & underscore).\bMatches a word boundary position between a word character and non-word character or position (start / end of string).\sMatches any whitespace character (spaces, tabs, line breaks).*Match0or more of the preceding token.(?=Matches a group after the main expression without including it in the result..Matches any character except line breaks.\1Matches the results of capture group #1 in step 2.
Note: It is important to use word boundaries here to avoid matching partial words.
Here's a link to regex demo and explaination : RegexDemo