首页javastringJava Data Type - 如何从字符串中多次出现的打印字

Java Data Type - 如何从字符串中多次出现的打印字

我们想知道如何从字符串中多次出现的打印字。
import java.util.HashMap;
import java.util.Map;

public class Main {
  public static void main(String[] args) {

    String sentence = "is this a sentence this is a test";
    String[] myStringArray = sentence.split("\\s"); // Split the sentence by
                                                    // space.

    Map<String, Integer> wordOccurrences = new HashMap<String, Integer>(
        myStringArray.length);

    for (String word : myStringArray) {
      if (wordOccurrences.containsKey(word)) {
        wordOccurrences.put(word, wordOccurrences.get(word) + 1);
      } else {
        wordOccurrences.put(word, 1);
      }
    }
    for (String word : wordOccurrences.keySet()) {
      if (wordOccurrences.get(word) > 1) {
        System.out.println("1b. - Tokens that occurs more than once: " + word
            + "\n");
      }
    }
  }
}