Ha KiM's Ha KiM's - 1 month ago 7
Java Question

remove repeated words from String Array

Good Morning

I write a function that calculates for me the frequency of a term:

public static int tfCalculator(String[] totalterms, String termToCheck) {
int count = 0; //to count the overall occurrence of the term termToCheck
for (String s : totalterms) {
if (s.equalsIgnoreCase(termToCheck)) {
count++;
}
}
return count;
}


and after that I use it on the code below to calculate every word from a
String[] words


for(String word:words){
int freq = tfCalculator(words, word);

System.out.println(word + "|" + freq);
mm+=word + "|" + freq+"\n";
}


well the problem that I have is that the words repeat here is for example the result:


  • cytoskeletal|2

  • network|1

  • enable|1

  • equal|1

  • spindle|1

  • cytoskeletal|2

  • ...

  • ...



so can someone help me to remove the repeated word and get as result like that:


  • cytoskeletal|2

  • network|1

  • enable|1

  • equal|1

  • spindle|1

  • ...

  • ...



Thank you very much!

Answer

I think here you want to print the frequency of each string in the array totalterms . I think using Map is a easier solution as in the single traversal of the array it will store the frequency of all the strings Check the following implementation.

public static void printFrequency(String[] totalterms)
{
    Map frequencyMap = new HashMap<String, Integer>();

    for (String string : totalterms) {
        if(frequencyMap.containsKey(string))
        {
            Integer count = (Integer)frequencyMap.get(string);
            frequencyMap.put(string, count+1);
        }
        else
        {
            frequencyMap.put(string, 1);
        }
    }

    Set <Entry<String, Integer>> elements= frequencyMap.entrySet();

    for (Entry<String, Integer> entry : elements) {
        System.out.println(entry.getKey()+"|"+entry.getValue());
    }
}
Comments