在字符串上找到重复的单词并计算重复次数

Han*_*ans 10 java string repeat

我需要在字符串上找到重复的单词,然后计算它们被重复的次数.所以基本上,如果输入字符串是这样的:

String s = "House, House, House, Dog, Dog, Dog, Dog";
Run Code Online (Sandbox Code Playgroud)

我需要创建一个没有重复的新字符串列表,并在其他地方保存每个单词的重复次数,如下所示:

新字符串:"House,Dog"

新的Int数组:[3,4]

有没有办法用Java轻松完成这项工作?我已经设法使用s.split()分隔字符串但是我如何计算重复并在新字符串上消除它们?谢谢!

Mar*_*ers 22

你已经完成了艰苦的工作.现在你可以使用a Map来计算出现次数:

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);
}
Run Code Online (Sandbox Code Playgroud)

使用map.get(word)会告诉你多次出现一个单词.您可以通过迭代来构造一个新列表map.keySet():

for ( String word : occurrences.keySet() ) {
  //do something with word
}
Run Code Online (Sandbox Code Playgroud)

请注意,您获得的顺序keySet是任意的.如果您需要按首次出现在输入字符串中的字词进行排序,则应使用a LinkedHashMap.