Word count repeated words

ProfessionalComputers

This calculator counts the number of unique words in a text (total number of words minus all word repetitions). It also counts a number of repeated words. It also can remove all the repetitions from the text.

PLANETCALC, Unique word calculator

Unique word calculator

Text

Text, which contains repeated words

Remove repeated words

Removes repeated words, starting from the second occurence.

Show quantity

To display number of words near a word.

Case sensitive

Exclude words

Words to be excluded from count

Unique word count

Text

Valid words

The file is very large. Browser slowdown may occur during loading and creation.

URL copied to clipboard

Similar calculators

  • • Count the number of words
  • • Tank volume
  • • Complex Fraction Simplifier
  • • Cryptarithmetic puzzle solver
  • • Conversion of pounds into inches
  • • Computers section ( 65 calculators )

 Computers Literature number of words unique words word word count words

PLANETCALC, Unique words count

Anton2021-09-30 12:26:11

Comments

Your message

Subscribe to comments notifications

You’ve got the hard work done. Now you can just use a Map to count the occurrences:

Map<String, Integer> occurrences = new HashMap<String, Integer>();

for ( String word : splitWords ) {
   Integer oldCount = occurrences.get(word);
   if ( oldCount == null ) {
      oldCount = 0;
   }
   occurrences.put(word, oldCount + 1);
}

Using map.get(word) will tell you many times a word occurred. You can construct a new list by iterating through map.keySet():

for ( String word : occurrences.keySet() ) {
  //do something with word
}

Note that the order of what you get out of keySet is arbitrary. If you need the words to be sorted by when they first appear in your input String, you should use a LinkedHashMap instead.

answered Jan 27, 2011 at 19:18

Mark Peters's user avatar

Mark PetersMark Peters

79.8k17 gold badges158 silver badges189 bronze badges

1

Try this,

public class DuplicateWordSearcher {
@SuppressWarnings("unchecked")
public static void main(String[] args) {

    String text = "a r b k c d se f g a d f s s f d s ft gh f ws w f v x s g h d h j j k f sd j e wed a d f";

    List<String> list = Arrays.asList(text.split(" "));

    Set<String> uniqueWords = new HashSet<String>(list);
    for (String word : uniqueWords) {
        System.out.println(word + ": " + Collections.frequency(list, word));
    }
}

}

answered Jul 17, 2013 at 6:27

Puja Mishra's user avatar

Puja MishraPuja Mishra

2451 gold badge3 silver badges8 bronze badges

public class StringsCount{

    public static void main(String args[]) {

        String value = "This is testing Program testing Program";

        String item[] = value.split(" ");

        HashMap<String, Integer> map = new HashMap<>();

        for (String t : item) {
            if (map.containsKey(t)) {
                map.put(t, map.get(t) + 1);

            } else {
                map.put(t, 1);
            }
        }
        Set<String> keys = map.keySet();
        for (String key : keys) {
            System.out.println(key);
            System.out.println(map.get(key));
        }

    }
}

PatJ's user avatar

PatJ

5,8961 gold badge31 silver badges37 bronze badges

answered Mar 23, 2015 at 17:51

javaCode555's user avatar

As mentioned by others use String::split(), followed by some map (hashmap or linkedhashmap) and then merge your result. For completeness sake putting the code.

import java.util.*;

public class Genric<E>
{
    public static void main(String[] args) 
    {
        Map<String, Integer> unique = new LinkedHashMap<String, Integer>();
        for (String string : "House, House, House, Dog, Dog, Dog, Dog".split(", ")) {
            if(unique.get(string) == null)
                unique.put(string, 1);
            else
                unique.put(string, unique.get(string) + 1);
        }
        String uniqueString = join(unique.keySet(), ", ");
        List<Integer> value = new ArrayList<Integer>(unique.values());

        System.out.println("Output = " + uniqueString);
        System.out.println("Values = " + value);

    }

    public static String join(Collection<String> s, String delimiter) {
        StringBuffer buffer = new StringBuffer();
        Iterator<String> iter = s.iterator();
        while (iter.hasNext()) {
            buffer.append(iter.next());
            if (iter.hasNext()) {
                buffer.append(delimiter);
            }
        }
        return buffer.toString();
    }
}

New String is Output = House, Dog

Int array (or rather list) Values = [3, 4] (you can use List::toArray) for getting an array.

answered Jan 28, 2011 at 3:08

Favonius's user avatar

FavoniusFavonius

13.8k3 gold badges54 silver badges94 bronze badges

1

Using java8

private static void findWords(String s, List<String> output, List<Integer> count){
    String[] words = s.split(", ");
    Map<String, Integer> map = new LinkedHashMap<>();
    Arrays.stream(words).forEach(e->map.put(e, map.getOrDefault(e, 0) + 1));
    map.forEach((k,v)->{
        output.add(k);
        count.add(v);
    });
}

Also, use a LinkedHashMap if you want to preserve the order of insertion

private static void findWords(){
    String s = "House, House, House, Dog, Dog, Dog, Dog";
    List<String> output = new ArrayList<>();
    List<Integer> count = new ArrayList<>();
    findWords(s, output, count);
    System.out.println(output);
    System.out.println(count);
}

Output

[House, Dog]
[3, 4]

answered Apr 27, 2019 at 5:51

Ankit Sharma's user avatar

Ankit SharmaAnkit Sharma

1,5661 gold badge13 silver badges21 bronze badges

If this is a homework, then all I can say is: use String.split() and HashMap<String,Integer>.

(I see you’ve found split() already. You’re along the right lines then.)

answered Jan 27, 2011 at 19:18

biziclop's user avatar

biziclopbiziclop

48.6k12 gold badges77 silver badges104 bronze badges

It may help you somehow.

String st="I am am not the one who is thinking I one thing at time";
String []ar = st.split("\s");
Map<String, Integer> mp= new HashMap<String, Integer>();
int count=0;

for(int i=0;i<ar.length;i++){
    count=0;

    for(int j=0;j<ar.length;j++){
        if(ar[i].equals(ar[j])){
        count++;                
        }
    }

    mp.put(ar[i], count);
}

System.out.println(mp);

Sky's user avatar

Sky

1,4251 gold badge15 silver badges24 bronze badges

answered May 25, 2017 at 8:19

RKP's user avatar

Once you have got the words from the string it is easy.
From Java 10 onwards you can try the following code:

import java.util.Arrays;
import java.util.stream.Collectors;

public class StringFrequencyMap {
    public static void main(String... args) {
        String[] wordArray = {"House", "House", "House", "Dog", "Dog", "Dog", "Dog"};
        var freq = Arrays.stream(wordArray)
                         .collect(Collectors.groupingBy(x -> x, Collectors.counting()));
        System.out.println(freq);
    }
}

Output:

{House=3, Dog=4}

answered Jun 21, 2018 at 6:33

user2173372's user avatar

user2173372user2173372

4535 silver badges17 bronze badges

You can use Prefix tree (trie) data structure to store words and keep track of count of words within Prefix Tree Node.

  #define  ALPHABET_SIZE 26
  // Structure of each node of prefix tree
  struct prefix_tree_node {
    prefix_tree_node() : count(0) {}
    int count;
    prefix_tree_node *child[ALPHABET_SIZE];
  };
  void insert_string_in_prefix_tree(string word)
  {
    prefix_tree_node *current = root;
    for(unsigned int i=0;i<word.size();++i){
      // Assuming it has only alphabetic lowercase characters
            // Note ::::: Change this check or convert into lower case
    const unsigned int letter = static_cast<int>(word[i] - 'a');

      // Invalid alphabetic character, then continue
      // Note :::: Change this condition depending on the scenario
      if(letter > 26)
        throw runtime_error("Invalid alphabetic character");

      if(current->child[letter] == NULL)
        current->child[letter] = new prefix_tree_node();

      current = current->child[letter];
    }
  current->count++;
  // Insert this string into Max Heap and sort them by counts
}

    // Data structure for storing in Heap will be something like this
    struct MaxHeapNode {
       int count;
       string word;
    };

After inserting all words, you have to print word and count by iterating Maxheap.

answered Jul 21, 2012 at 1:56

Dev Null Fin's user avatar

Dev Null FinDev Null Fin

1731 gold badge3 silver badges16 bronze badges

//program to find number of repeating characters in a string
//Developed by Subash<subash_senapati@ymail.com>


import java.util.Scanner;

public class NoOfRepeatedChar

{

   public static void main(String []args)

   {

//input through key board

Scanner sc = new Scanner(System.in);

System.out.println("Enter a string :");

String s1= sc.nextLine();


    //formatting String to char array

    String s2=s1.replace(" ","");
    char [] ch=s2.toCharArray();

    int counter=0;

    //for-loop tocompare first character with the whole character array

    for(int i=0;i<ch.length;i++)
    {
        int count=0;

        for(int j=0;j<ch.length;j++)
        {
             if(ch[i]==ch[j])
                count++; //if character is matching with others
        }
        if(count>1)
        {
            boolean flag=false;

            //for-loop to check whether the character is already refferenced or not 
            for (int k=i-1;k>=0 ;k-- )
            {
                if(ch[i] == ch[k] ) //if the character is already refferenced
                    flag=true;
            }
            if( !flag ) //if(flag==false) 
                counter=counter+1;
        }
    }
    if(counter > 0) //if there is/are any repeating characters
            System.out.println("Number of repeating charcters in the given string is/are " +counter);
    else
            System.out.println("Sorry there is/are no repeating charcters in the given string");
    }
}

Jean's user avatar

Jean

7,5936 gold badges43 silver badges58 bronze badges

answered Mar 24, 2013 at 18:05

subash's user avatar

public static void main(String[] args) {
    String s="sdf sdfsdfsd sdfsdfsd sdfsdfsd sdf sdf sdf ";
    String st[]=s.split(" ");
    System.out.println(st.length);
    Map<String, Integer> mp= new TreeMap<String, Integer>();
    for(int i=0;i<st.length;i++){

        Integer count=mp.get(st[i]);
        if(count == null){
            count=0;
        }           
        mp.put(st[i],++count);
    }
   System.out.println(mp.size());
   System.out.println(mp.get("sdfsdfsd"));


}

answered Aug 29, 2013 at 5:29

K Madhu Sudhan Reddy's user avatar

If you pass a String argument it will count the repetition of each word

/**
 * @param string
 * @return map which contain the word and value as the no of repatation
 */
public Map findDuplicateString(String str) {
    String[] stringArrays = str.split(" ");
    Map<String, Integer> map = new HashMap<String, Integer>();
    Set<String> words = new HashSet<String>(Arrays.asList(stringArrays));
    int count = 0;
    for (String word : words) {
        for (String temp : stringArrays) {
            if (word.equals(temp)) {
                ++count;
            }
        }
        map.put(word, count);
        count = 0;
    }

    return map;

}

output:

 Word1=2, word2=4, word2=1,. . .

answered May 8, 2014 at 4:26

loknath's user avatar

loknathloknath

1,36216 silver badges25 bronze badges

import java.util.HashMap;
import java.util.LinkedHashMap;

public class CountRepeatedWords {

    public static void main(String[] args) {
          countRepeatedWords("Note that the order of what you get out of keySet is arbitrary. If you need the words to be sorted by when they first appear in your input String, you should use a LinkedHashMap instead.");
    }

    public static void countRepeatedWords(String wordToFind) {
        String[] words = wordToFind.split(" ");
        HashMap<String, Integer> wordMap = new LinkedHashMap<String, Integer>();

        for (String word : words) {
            wordMap.put(word,
                (wordMap.get(word) == null ? 1 : (wordMap.get(word) + 1)));
        }

            System.out.println(wordMap);
    }

}

Illidanek's user avatar

Illidanek

9981 gold badge18 silver badges32 bronze badges

answered Aug 12, 2014 at 11:40

Purushotham's user avatar

I hope this will help you

public void countInPara(String str) {

    Map<Integer,String> strMap = new HashMap<Integer,String>();
    List<String> paraWords = Arrays.asList(str.split(" "));
    Set<String> strSet = new LinkedHashSet<>(paraWords);
    int count;

    for(String word : strSet) {
        count = Collections.frequency(paraWords, word);
        strMap.put(count, strMap.get(count)==null ? word : strMap.get(count).concat(","+word));
    }

    for(Map.Entry<Integer,String> entry : strMap.entrySet())
        System.out.println(entry.getKey() +" :: "+ entry.getValue());
}

answered Oct 14, 2014 at 13:36

Harshit Thacker's user avatar

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DuplicateWord {

    public static void main(String[] args) {
        String para = "this is what it is this is what it can be";
        List < String > paraList = new ArrayList < String > ();
        paraList = Arrays.asList(para.split(" "));
        System.out.println(paraList);
        int size = paraList.size();

        int i = 0;
        Map < String, Integer > duplicatCountMap = new HashMap < String, Integer > ();
        for (int j = 0; size > j; j++) {
            int count = 0;
            for (i = 0; size > i; i++) {
                if (paraList.get(j).equals(paraList.get(i))) {
                    count++;
                    duplicatCountMap.put(paraList.get(j), count);
                }

            }

        }
        System.out.println(duplicatCountMap);
        List < Integer > myCountList = new ArrayList < > ();
        Set < String > myValueSet = new HashSet < > ();
        for (Map.Entry < String, Integer > entry: duplicatCountMap.entrySet()) {
            myCountList.add(entry.getValue());
            myValueSet.add(entry.getKey());
        }
        System.out.println(myCountList);
        System.out.println(myValueSet);
    }

}

Input: this is what it is this is what it can be

Output:

[this, is, what, it, is, this, is, what, it, can, be]

{can=1, what=2, be=1, this=2, is=3, it=2}

[1, 2, 1, 2, 3, 2]

[can, what, be, this, is, it]

Debosmit Ray's user avatar

Debosmit Ray

5,1682 gold badges27 silver badges43 bronze badges

answered Mar 29, 2016 at 7:08

RishiKesh Pathak's user avatar

RishiKesh PathakRishiKesh Pathak

2,0821 gold badge17 silver badges23 bronze badges

1

import java.util.HashMap;
import java.util.Scanner;
public class class1 {
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String inpStr = in.nextLine();
    int key;

    HashMap<String,Integer> hm = new HashMap<String,Integer>();
    String[] strArr = inpStr.split(" ");

    for(int i=0;i<strArr.length;i++){
        if(hm.containsKey(strArr[i])){
            key = hm.get(strArr[i]);
            hm.put(strArr[i],key+1);

        }
        else{
            hm.put(strArr[i],1);
        }   
    }
    System.out.println(hm);
}

}

answered Apr 16, 2016 at 5:15

chirag kansal's user avatar

3

Please use the below code. It is the most simplest as per my analysis. Hope you will like it:

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

public class MostRepeatingWord {

    String mostRepeatedWord(String s){
        String[] splitted = s.split(" ");
        List<String> listString = Arrays.asList(splitted);
        Set<String> setString = new HashSet<String>(listString);
        int count = 0;
        int maxCount = 1;
        String maxRepeated = null;
        for(String inp: setString){
            count = Collections.frequency(listString, inp);
            if(count > maxCount){
                maxCount = count;
                maxRepeated = inp;
            }
        }
        return maxRepeated;
    }
    public static void main(String[] args) 
    {       
        System.out.println("Enter The Sentence: ");
        Scanner s = new Scanner(System.in);
        String input = s.nextLine();
        MostRepeatingWord mrw = new MostRepeatingWord();
        System.out.println("Most repeated word is: " + mrw.mostRepeatedWord(input));

    }
}

answered May 16, 2016 at 6:20

Tarun Majumder's user avatar

package day2;

import java.util.ArrayList;
import java.util.HashMap;`enter code here`
import java.util.List;

public class DuplicateWords {

    public static void main(String[] args) {
        String S1 = "House, House, House, Dog, Dog, Dog, Dog";
        String S2 = S1.toLowerCase();
        String[] S3 = S2.split("\s");

        List<String> a1 = new ArrayList<String>();
        HashMap<String, Integer> hm = new HashMap<>();

        for (int i = 0; i < S3.length - 1; i++) {

            if(!a1.contains(S3[i]))
            {
                a1.add(S3[i]);
            }
            else
            {
                continue;
            }

            int Count = 0;

            for (int j = 0; j < S3.length - 1; j++)
            {
                if(S3[j].equals(S3[i]))
                {
                    Count++;
                }
            }

            hm.put(S3[i], Count);
        }

        System.out.println("Duplicate Words and their number of occurrences in String S1 : " + hm);
    }
}

Eloims's user avatar

Eloims

5,0364 gold badges25 silver badges40 bronze badges

answered Jul 12, 2016 at 8:55

Manikanta Bondu's user avatar

public class Counter {

private static final int COMMA_AND_SPACE_PLACE = 2;

private String mTextToCount;
private ArrayList<String> mSeparateWordsList;

public Counter(String mTextToCount) {
    this.mTextToCount = mTextToCount;

    mSeparateWordsList = cutStringIntoSeparateWords(mTextToCount);
}

private ArrayList<String> cutStringIntoSeparateWords(String text)
{
    ArrayList<String> returnedArrayList = new ArrayList<>();


    if(text.indexOf(',') == -1)
    {
        returnedArrayList.add(text);
        return returnedArrayList;
    }

    int position1 = 0;
    int position2 = 0;

    while(position2 < text.length())
    {
        char c = ',';
        if(text.toCharArray()[position2] == c)
        {
            String tmp = text.substring(position1, position2);
            position1 += tmp.length() + COMMA_AND_SPACE_PLACE;
            returnedArrayList.add(tmp);
        }
        position2++;
    }

    if(position1 < position2)
    {
        returnedArrayList.add(text.substring(position1, position2));
    }

    return returnedArrayList;
}

public int[] countWords()
{
    if(mSeparateWordsList == null) return null;


    HashMap<String, Integer> wordsMap = new HashMap<>();

    for(String s: mSeparateWordsList)
    {
        int cnt;

        if(wordsMap.containsKey(s))
        {
            cnt = wordsMap.get(s);
            cnt++;
        } else {
            cnt = 1;
        }
        wordsMap.put(s, cnt);
    }                
    return printCounterResults(wordsMap);
}

private int[] printCounterResults(HashMap<String, Integer> m)
{        
    int index = 0;
    int[] returnedIntArray = new int[m.size()];

    for(int i: m.values())
    {
        returnedIntArray[index] = i;
        index++;
    }

    return returnedIntArray;

}

}

answered Sep 22, 2016 at 11:11

Volodymyr Shalashenko's user avatar

/*count no of Word in String using TreeMap we can use HashMap also but word will not display in sorted order */

import java.util.*;

public class Genric3
{
    public static void main(String[] args) 
    {
        Map<String, Integer> unique = new TreeMap<String, Integer>();
        String string1="Ram:Ram: Dog: Dog: Dog: Dog:leela:leela:house:house:shayam";
        String string2[]=string1.split(":");

        for (int i=0; i<string2.length; i++)
        {
            String string=string2[i];
            unique.put(string,(unique.get(string) == null?1:(unique.get(string)+1)));
        }

        System.out.println(unique);
    }
}      

N00b Pr0grammer's user avatar

answered Feb 4, 2012 at 16:42

Dalee Bisen's user avatar

//program to find number of repeating characters in a string
//Developed by Rahul Lakhmara

import java.util.*;

public class CountWordsInString {
    public static void main(String[] args) {
        String original = "I am rahul am i sunil so i can say am i";
        // making String type of array
        String[] originalSplit = original.split(" ");
        // if word has only one occurrence
        int count = 1;
        // LinkedHashMap will store the word as key and number of occurrence as
        // value
        Map<String, Integer> wordMap = new LinkedHashMap<String, Integer>();

        for (int i = 0; i < originalSplit.length - 1; i++) {
            for (int j = i + 1; j < originalSplit.length; j++) {
                if (originalSplit[i].equals(originalSplit[j])) {
                    // Increment in count, it will count how many time word
                    // occurred
                    count++;
                }
            }
            // if word is already present so we will not add in Map
            if (wordMap.containsKey(originalSplit[i])) {
                count = 1;
            } else {
                wordMap.put(originalSplit[i], count);
                count = 1;
            }
        }

        Set word = wordMap.entrySet();
        Iterator itr = word.iterator();
        while (itr.hasNext()) {
            Map.Entry map = (Map.Entry) itr.next();
            // Printing
            System.out.println(map.getKey() + " " + map.getValue());
        }
    }
}

answered Jan 29, 2017 at 10:06

Rahul Lakhmara's user avatar

1

    public static void main(String[] args){
    String string = "elamparuthi, elam, elamparuthi";
    String[] s = string.replace(" ", "").split(",");
    String[] op;
    String ops = "";

    for(int i=0; i<=s.length-1; i++){
        if(!ops.contains(s[i]+"")){
            if(ops != "")ops+=", "; 
            ops+=s[i];
        }

    }
    System.out.println(ops);
}

answered Mar 16, 2017 at 13:40

Elamparuthi's user avatar

1

For Strings with no space, we can use the below mentioned code

private static void findRecurrence(String input) {
    final Map<String, Integer> map = new LinkedHashMap<>();
    for(int i=0; i<input.length(); ) {
        int pointer = i;
        int startPointer = i;
        boolean pointerHasIncreased = false;
        for(int j=0; j<startPointer; j++){
            if(pointer<input.length() && input.charAt(j)==input.charAt(pointer) && input.charAt(j)!=32){
                pointer++;
                pointerHasIncreased = true;
            }else{
                if(pointerHasIncreased){
                    break;
                }
            }
        }
        if(pointer - startPointer >= 2) {
            String word = input.substring(startPointer, pointer);
            if(map.containsKey(word)){
                map.put(word, map.get(word)+1);
            }else{
                map.put(word, 1);
            }
            i=pointer;
        }else{
            i++;
        }
    }
    for(Map.Entry<String, Integer> entry : map.entrySet()){
        System.out.println(entry.getKey() + " = " + (entry.getValue()+1));
    }
}

Passing some input as «hahaha» or «ba na na» or «xxxyyyzzzxxxzzz» give the desired output.

answered Sep 3, 2017 at 12:22

Puneet Akhouri's user avatar

Hope this helps :

public static int countOfStringInAText(String stringToBeSearched, String masterString){

    int count = 0;
    while (masterString.indexOf(stringToBeSearched)>=0){
      count = count + 1;
      masterString = masterString.substring(masterString.indexOf(stringToBeSearched)+1);
    }
    return count;
}

Sam's user avatar

Sam

1,5422 gold badges13 silver badges27 bronze badges

answered Jun 28, 2018 at 15:03

Akhil's user avatar

AkhilAkhil

12 bronze badges

package string;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class DublicatewordinanArray {
public static void main(String[] args) {
String str = "This is Dileep Dileep Kumar Verma Verma";
DuplicateString(str);
    }
public static void DuplicateString(String str) {
String word[] = str.split(" ");
Map < String, Integer > map = new HashMap < String, Integer > ();
for (String w: word)
if (!map.containsKey(w)) {
map.put(w, 1);
    }
else {
map.put(w, map.get(w) + 1);
        }
Set < Map.Entry < String, Integer >> entrySet = map.entrySet();
 for (Map.Entry < String, Integer > entry: entrySet)
if (entry.getValue() > 1) {
 System.out.printf("%s : %d %n", entry.getKey(), entry.getValue());
}
 }
}

answered Sep 9, 2018 at 16:35

Dileep Verma's user avatar

1

Using Java 8 streams collectors:

public static Map<String, Integer> countRepetitions(String str) {
    return Arrays.stream(str.split(", "))
        .collect(Collectors.toMap(s -> s, s -> 1, (a, b) -> a + 1));
}

Input: "House, House, House, Dog, Dog, Dog, Dog, Cat"

Output: {Cat=1, House=3, Dog=4}

answered Feb 13, 2019 at 4:44

panibrat's user avatar

please try these it may be help for you.

public static void main(String[] args) {
        String str1="House, House, House, Dog, Dog, Dog, Dog";
        String str2=str1.replace(",", "");
        Map<String,Integer> map=findFrquenciesInString(str2);
        Set<String> keys=map.keySet();
        Collection<Integer> vals=map.values();
        System.out.println(keys);
        System.out.println(vals);
    }

private static Map<String,Integer> findFrquenciesInString(String str1) {
        String[] strArr=str1.split(" ");
        Map<String,Integer> map=new HashMap<>();
        for(int i=0;i<strArr.length;i++) {
            int count=1;
            for(int j=i+1;j<strArr.length;j++) {
                if(strArr[i].equals(strArr[j]) && strArr[i]!="-1") {
                    strArr[j]="-1";
                    count++;
                }
            }
            if(count>1 && strArr[i]!="-1") {
                map.put(strArr[i], count);
                strArr[i]="-1";
            }
        }
        return map;
    }

answered Jan 24, 2020 at 10:34

hitesh bariya's user avatar

1

as introduction of stream has changed the way we code; i would like to add some of the ways of doing this using it

    String[] strArray = str.split(" ");
    
    //1. All string value with their occurrences
    Map<String, Long> counterMap = 
            Arrays.stream(strArray).collect(Collectors.groupingBy(e->e, Collectors.counting()));

    //2. only duplicating Strings
    Map<String, Long> temp = counterMap.entrySet().stream().filter(map->map.getValue() > 1).collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue()));
    System.out.println("test : "+temp);
    
    //3. List of Duplicating Strings
    List<String> masterStrings = Arrays.asList(strArray);
    Set<String> duplicatingStrings = 
            masterStrings.stream().filter(i -> Collections.frequency(masterStrings, i) > 1).collect(Collectors.toSet());

answered Sep 17, 2020 at 15:41

Krupali's user avatar

Use Function.identity() inside Collectors.groupingBy and store everything in a MAP.

String a  = "Gini Gina Gina Gina Gina Protijayi Protijayi "; 
        Map<String, Long> map11 = Arrays.stream(a.split(" ")).collect(Collectors
                .groupingBy(Function.identity(),Collectors.counting()));
        System.out.println(map11);

// output => {Gina=4, Gini=1, Protijayi=2}

In Python we can use collections.Counter()

a = "Roopa Roopi  loves green color Roopa Roopi"
words = a.split()

wordsCount = collections.Counter(words)
for word,count in sorted(wordsCount.items()):
    print('"%s" is repeated %d time%s.' % (word,count,"s" if count > 1 else "" ))

Output :

«Roopa» is repeated 2 times.
«Roopi» is repeated 2 times.
«color» is repeated 1 time.
«green» is repeated 1 time.
«loves» is repeated 1 time.

answered Jul 31, 2019 at 6:55

Soudipta Dutta's user avatar

Soudipta DuttaSoudipta Dutta

1,2571 gold badge12 silver badges7 bronze badges

Online calculator to count the total, unique and repeated number of words in a given text. The counter lists all the words with the number of occurrences in the sentences.

Count Total, Unique Number of Words and Repeated Words in a Text

Online calculator to count the total, unique and repeated number of words in a given text. The counter lists all the words with the number of occurrences in the sentences.

Code to add this calci to your website Expand embed code Minimize embed code

Total, unique and also repeated words using word count calculation is made easier here.

World’s simplest online word frequency calculator for web developers and programmers. Just paste your text in the form below, press the Calculate Word Frequency button, and you’ll get individual word statistics. Press a button – get the word count. No ads, nonsense, or garbage.

Announcement: We just launched TECHURLS – a simple and fun tech news aggregator. Check it out!

Using a Word Frequency Calculator in Cross-browser Testing

A word frequency counter can be useful if you’re doing cross-browser testing. For example, if you have made a web application that accepts user comments, you may want to prevent users from repeating the same words in the comments too many times. You can use this utility to write test cases for catching comments with many repeated words. Also, this program can be useful if you’re doing statistical text analysis or optimizing the text for SEO. Additionally, you can use this program to tell which language the given text is written in. Each language has some words appearing more often than others and this distribution of words is unique to each language.

Pro tip: You can use ?input=text query argument to pass text to tools.

Following Java program to counts how many times a word appears in a String or find repeated words. It can help you in to find the most frequent words in a string also check the count which will be equal to one for unique words.

Step1: Split the words from the input String using the split() method.

Step2: Iterate the loop for counting the repeated words.

countwords.java

package String;

public class CountWords 
{

   public static void main(String[] args)
   {
      String input="Welcome to Java Session Session Session";  //Input String 
      String[] words=input.split(" ");  //Split the word from String
      int wrc=1;    //Variable for getting Repeated word count
      
      for(int i=0;i<words.length;i++) //Outer loop for Comparison       
      {
         for(int j=i+1;j<words.length;j++) //Inner loop for Comparison
         {
            
         if(words[i].equals(words[j]))  //Checking for both strings are equal
            {
               wrc=wrc+1;    //if equal increment the count
               words[j]="0"; //Replace repeated words by zero
            }
         }
         if(words[i]!="0")
         System.out.println(words[i]+"--"+wrc); //Printing the word along with count
         wrc=1;
         
        }  
         
   }

}

Output:

Welcome--1
to--1
Java--1
Session--3

Like this post? Please share to your friends:
  • Word count print что это
  • Word count one page
  • Word count one note
  • Word count on word online
  • Word count on an essay