Java Data Type How to - Print words which occurs more than once from a string








Question

We would like to know how to print words which occurs more than once from a string.

Answer

import java.util.HashMap;
import java.util.Map;
//  w w  w .ja v  a  2 s  .co m
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");
      }
    }
  }
}