program to count the occurrences of each character in a String

There are multiple way to count the occurrences of each character in a String and also it should not print repeatedly occurrences of duplicate characters.

From containsKey method :-

  • Create the HashMap class object.
  • Traverse the input string and convert into character from str.charAt() method.
  • Now call containsKey method of Map class.it take character through str.charAt(i) method and check which key we are storing inside hashmap that is present or not.if not present then they add else not add.

From compute and lambda method :-

  • Create the HashMap class object.
  • Traverse the input string and convert into character from str.charAt() method.
  • The compute() method computes a new value for the provided key and returns one of the following:
  • The new value associated with key.
  • If key does not have an associated value, then compute() returns null.

From groupingBy and counting method :-

  • Here first convert string to character and store in IntStream.
  • Now convert IntStream data to map from mapToObj method and store in stream.
  • We call Collectors.groupingBy method,they grouping the character and Collectors.counting method count occurrences of each character.
				
					import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class CharCount {
	public static void main(String[] args) {
		String str = "pppmmfgrrtyy";

		// from containsKey method
		Map<Character, Integer> mp = new HashMap<Character, Integer>();
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if (mp.containsKey(c)) {
				mp.put(c, mp.get(c) + 1);
			} else {
				mp.put(c, 1);
			}
		}
		System.out.println("number of Occurrence character from containsKey method :- " + mp);

		// from compute and lambda method
		Map<Character, Integer> hm = new HashMap<Character, Integer>();
		for (int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			hm.compute(ch, (key, value) -> (value == null) ? 1 : value + 1);
		}
		System.out.println("number of Occurrence character from compute and lambda method :- " + hm);

		// from groupingBy and counting method
		IntStream in = str.chars();
		Stream<Character> f = in.mapToObj(ch -> (char) ch);
		Map<Character, Long> z = f.collect(Collectors.groupingBy(ch -> ch, Collectors.counting()));
		System.out.println("number of Occurrence character from groupingBy and counting method :- " + z);
	}
}

				
			

Output :-
number of Occurrence character from containsKey method :- {p=3, r=2, t=1, f=1, g=1, y=2, m=2}
number of Occurrence character from compute and lambda method :- {p=3, r=2, t=1, f=1, g=1, y=2, m=2}
number of Occurrence character from groupingBy and counting method :- {p=3, r=2, t=1, f=1, g=1, y=2, m=2}