Tuesday 5 February 2019

2. Count occurrences of character in string java using hashmap

Description:
Write a sample code to Count occurrences of character in string.

Code:
?
1
2
3
4
5
6
7
8
9
10

import java.util.HashMap; public class NO_of_Occurance { public static void main(String[] args) { String str = "Programming"; HashMap<Character, Integer> map = new HashMap<>(); for (char ch : str.toCharArray()) { if (map.containsKey(ch)) { int val = map.get(ch); map.put(ch, val + 1); } else { map.put(ch, 1); } } System.out.println(map); } }





Output:
{P=1, a=1, r=2, g=2, i=1, m=2, n=1, o=1}

No comments:

Post a Comment