How to get distinct characters and their count in a String?

How to get distinct characters and their count in a String?

Example:

Input: str = "Hello Words";

Approach

Java


import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class CharCount {
    public static void main(String[] args) {

        String str = "Hello Words";
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();

        for (int i = 0; i < str.length(); i++) {
            map.put(str.charAt(i), map.getOrDefault(str.charAt(i), 0) + 1);
        }

        // sort the map using value
        map = map.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(
                Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o2V, o1V) -> o2V, LinkedHashMap::new));

        map.forEach((a, b) -> System.out.println(a + " " + b));

    }
}

Output

l 2
o 2
  1
r 1
s 1
d 1
e 1
W 1
H 1


No comments:

Post a Comment