競技プログラミングの問題を解く際の時間短縮のため、主題のメソッドを作成した。
// Stringの配列の中で、単語の出現回数をカウントする。 Map<String, Integer> countWordsAppearance(String[] words) { if (words == null || words.length == 0) { throw new IllegalArgumentException("Input words is null or empty."); } Map<String, Integer> wordToCount = new HashMap<>(); for (String word : words) { if (wordToCount.containsKey(word)) { // 2回目以降 int count = wordToCount.get(word); wordToCount.put(word, ++count); } else { // 初回 wordToCount.put(word, new Integer(1)); } } return wordToCount; }
カウント結果は、単語(String) ⇒ 出現回数(Integer) のマップとして返す。結果を参照する場合は、以下のようにして取り出す。
Map<String, Integer> result = countWordsAppearance(words); int count = result.get("aaa");
ちなみに、Javaでは、MapのValueにはプリミティブ型は使用できないので、int 型ではなく Integer型を使っている。