remove duplicate words from string in java

realNameHidden - Apr 27 '23 - - Dev Community



import java.util.*;
import java.lang.*;
class Demo{
    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();
    }   

}


Enter fullscreen mode Exit fullscreen mode

Image description

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .