remove duplicate words from string in java
For Explanation Watch Video:
Program::
import java.util.*;
class College
{
public static void main(String[] args){
String sen = "Sam went went to to to his business";
String[] arr = sen.split(" ");
//arr={Sam,went,went,to,to ,to ,his ,business};
Set<String> s = new LinkedHashSet<String>();
for(int i=0;i<arr.length;i++){
s.add(arr[i]);
}
for(String ss:s){
System.out.print(ss+" ");
}
System.out.println();
}
}
o/p: Sam went to his business
Using Java 8
import java.util.*;
class College
{
public static void main(String[] args){
String sen = "Sam went went to to to his business";
sen = Arrays.stream(sen.split(" ")).distinct().collect(Collectors.joining(" ");
}
}
Comments
Post a Comment