how to remove duplicates in a string java 8 code example
Example 1: java program to remove duplicate words in a string
String fullString = "lol lol";
String[] words = fullString.split("\\W+");
StringBuilder stringBuilder = new StringBuilder();
Set<String> wordsHashSet = new HashSet<>();
for (String word : words) {
if (wordsHashSet.contains(word.toLowerCase())) continue;
wordsHashSet.add(word.toLowerCase());
stringBuilder.append(word).append(" ");
}
String nonDuplicateString = stringBuilder.toString().trim();
Example 2: remove duplicate string collection in java
String str2 = "ABABABCDEF";
String[] arr2 = str2.split("");
str2 = new LinkedHashSet<>(Arrays.asList(arr2)).toString().replace(", ", "");
System.out.println(str2);