Algorithm

자바 HashMap에 문자열 넣었을 때 문자별 개수 구하여 출력

OOOooOOoo·2020년 6월 11일·조회 82,501

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));
		}
	}
}

댓글 0

로그인 후 댓글을 남길 수 있습니다.

아직 댓글이 없습니다.