Monday, 10 September 2018

How to find duplicate words in a given sentence or in a string using java

package com.java.collections;

import java.util.HashMap;
import java.util.Iterator;

public class DuplicateString {
   
    static void findDuplicateWord(String str) {
       
        HashMap<String, Integer> hm = new HashMap<>();
       
        String[] s = str.split(" ");
       
        for(String tempString : s)
        {
            if(hm.get(tempString)!=null)
            {
                hm.put(tempString, hm.get(tempString)+1);
            }
            else
            {
                hm.put(tempString, 1);
            }
           
        }
         //   System.out.println(hm);
        Iterator<String> tempString = hm.keySet().iterator();
        while(tempString.hasNext())
        {
            String temp = tempString.next();
            if(hm.get(temp)>1)
            {
                System.out.println("the word " + temp + " appeared " + hm.get(temp) + " times");
            }
        }
    }

    public static void main(String[] args) {
       
        findDuplicateWord("i i am am java java and and");

    }

}

No comments:

Post a Comment

If you Like my blog Spread it and help friends for whom this blog is useful for their career.