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<CharacterIntegermap = new HashMap<CharacterInteger>();

        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

2
2
  1
1
1
1
1
1
1


No comments:

Post a Comment