Finding repeated words on a string and counting the repetitions

后端 未结 29 922
梦谈多话
梦谈多话 2021-02-05 17:49

I need to find repeated words on a string, and then count how many times they were repeated. So basically, if the input string is this:

String s = \"House, House         


        
29条回答
  •  花落未央
    2021-02-05 18:17

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

    Map occurrences = new HashMap();
    
    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.

提交回复
热议问题