1. 개요

자바 Map에 담긴 문자열 개수를 구하는 로직이다.

2. 코드

package io.sarc;

import java.util.HashMap;
import java.util.Map;

public class HashMapIntTest {
    Map<String, Integer> freqMap = new HashMap<String, Integer>();

    public static void main(String[] args) {
        HashMapIntTest hashMapIntTest = new HashMapIntTest();

        hashMapIntTest.mapExec("abc");
        hashMapIntTest.mapExec("def");
        hashMapIntTest.mapExec("acd");
        hashMapIntTest.mapExec("def");

        hashMapIntTest.printMap();
    }

    private void mapExec(String word) {
        Integer count = freqMap.get(word);

        if (count == null) {
            freqMap.put(word, 1);
        } else {
            freqMap.put(word, count + 1);
        }
    }

    private void printMap() {
        for (String s : freqMap.keySet()) {
            System.out.println(s + " = " + freqMap.get(s));
        }
    }
}