Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Saturday, 7 January 2017

Write a java program to find the duplicate words and their number of occurrences in a String ?

Here we write a program to count number of repeated words in sentence. For Example if the string is "I had had to go the store" then the output will come as word "had" = 2 .

Example :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class CountDuplicateWords {

 public static void getDuplicate(String str){
  String[] words = str.split(" ");
  Map<String, Integer> map = new HashMap<>();
  
  for(int i=0;i<words.length;i++){
   String s1 = words[i].toLowerCase();
   if(map.containsKey(s1)){
    map.put(s1, map.get(s1)+1);
   }
   else{
    map.put(s1, 1);
   }
  }
  Iterator it = map.entrySet().iterator();
  while(it.hasNext()){
   Entry en = (Entry) it.next();
   if(map.get(en.getKey()) > 1){
    System.out.println(en.getKey()+"\t"+en.getValue());
   }
  }
 }
 public static void main(String[] args) {
  CountDuplicateWords.getDuplicate("I had had to go the store");
  CountDuplicateWords.getDuplicate("Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo");
 }
}

Output :

had 2
buffalo 8


      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Share this Blog with yours Friends !!

No comments:

Post a Comment