Thursday, 20 April 2017

Java program to find duplicate strings present in a sentence

Given String: This is Rajneesh This and will That is This
Required OUTPUTThis, is

Source File:

package String_Programs;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class DuplicateString {
       public static void duplicateString(String str){
              Set<String> duplicateSet = new HashSet<String>()
              List<String> duplicateList = new ArrayList<String>();
              String[] strArray = str.split(" ");
              for(int i=0;i<strArray.length;i++){
                     for(int j=i+1;j<strArray.length;j++){
              System.out.println("List bucket data :" +duplicateList);
              System.out.println("Set bucket data :"  +duplicateSet);
       public static void main(String[] args) {
              duplicateString("This is Rajneesh This and will That is This");


List bucket data :[This, This, is, This]
Set bucket data :[This, is]

The output between List and Set calls for a discussion. Have a look and try to figure out what's the difference?

1 comment:

  1. Your Time complexity is O(n^2).
    It can be improved to O(n).


If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.