Remove Duplicate Words from String in java
package govind;
import java.util.Arrays;
import java.util.LinkedHashSet;
public class RemoveDuplicateWords {
public static String removeDuplicateWords(String str)
{
System.out.println("Original String="+str);
String[] strarray = str.split("\\s+");
LinkedHashSet<String> lhs=new LinkedHashSet<>(Arrays.asList(strarray));
StringBuilder sb=new StringBuilder();
int index=0;
for(String s1:lhs)
{
if(index>0)
sb.append(" ");
sb.append(s1);
index++;
}
str=sb.toString();
System.out.println("After Removing Duplicate Words");
return str ;
}
public static void main(String[] args) {
String removeduplicate = RemoveDuplicateWords.removeDuplicateWords("My name is khan and this khan is my title");
System.out.println(removeduplicate);
}
}
o/p:-----------------------------------------------
Original String=My name is khan and this khan is my title
My name is khan and this my title
==========================================================================================================================================
package govind;
import java.util.Arrays;
import java.util.LinkedHashSet;
public class RemoveDuplicateWordsByShortCut
{
public static String removeDuplicateWords(String str)
{
System.out.println("Original String="+str);
str=new LinkedHashSet<>(Arrays.asList(str.split("\\s+"))).toString().replaceAll("[\\[\\],]", "");
System.out.println(str);
return str;
}
public static void main(String[] args) {
String removeduplicate = RemoveDuplicateWordsByShortCut.removeDuplicateWords("My name is khan and this khan is my title");
System.out.println(removeduplicate);
}
}
o/p:-----------------------------------------------
Original String=My name is khan and this khan is my title
My name is khan and this my title
==============================================================================================================================================
package govind;
import java.util.Arrays;
import java.util.stream.Collectors;
public class RemoveDuplicateWordInJava8 {
public static String removeDuplicateWords(String str)
{
System.out.println("Original String="+str);
str=Arrays.stream(str.split("\\s+")).distinct().collect(Collectors.joining(" "));
return str;
}
public static void main(String[] args) {
String removeduplicate = RemoveDuplicateWordInJava8.removeDuplicateWords("My name is khan and this khan is my title");
System.out.println(removeduplicate);
}
}
o/p:-----------------------------------------------
Original String=My name is khan and this khan is my title
My name is khan and this my title
=============================================================================================================================================
No comments:
Post a Comment