Find Frequency Of Character In String Using Java

In this video we will see how to find frequency of character in string using Java and HashMap. We will not apply case sensitivity in this example but its upto you.

So here we go.


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

public class FrequencyOfCharacter {

	public static void main(String[] args) {
		String str = "FOotball";
		str = str.toLowerCase();
		
		Map<Character, Integer> map = new HashMap<Character, Integer>();
		
		for (char ch : str.toCharArray()) {
			
			if (map.get(ch) == null) {
				map.put(ch, 1);
			} else {
				map.put(ch, map.get(ch) + 1);
			}
			
		}
		
		map.forEach((key, value) -> {
			System.out.println(key + " occured " + value);
		});
	}

}


0 Comments