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 valuemap = 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 2o 21r 1s 1d 1e 1W 1H 1
No comments:
Post a Comment