Find duplicate characters in a String and count the number of occurances using Java

前端 未结 30 2520
遇见更好的自我
遇见更好的自我 2020-12-14 11:47

How can I find the number of occurrences of a character in a string?

For example: The quick brown fox jumped over the lazy dog.

Some example

30条回答
  •  鱼传尺愫
    2020-12-14 12:31

    Finding the duplicates in a String:

    Example 1 : Using HashMap

    public class a36 {
        public static void main(String[] args) {
            String a = "Gini Rani";
            fix(a);
        }//main
        public static void fix(String a ){
            Map map = new HashMap<>();
            for (int i = 0; i  list = new ArrayList<>();
           Set > entrySet = map.entrySet();
    
           for (  Map.Entry entry : entrySet) {
                 list.add( entry.getKey()  ); 
    
                 System.out.printf(  " %s : %d %n" ,  entry.getKey(), entry.getValue()           );
           }//for
           System.out.println("Duplicate elements => " + list);
    
        }//fix
    }
    

    Example 2 : using Arrays.stream() in Java 8

    public class a37 {
        public static void main(String[] args) {
            String aa = "Protijayi Gini";
            String[] stringarray = aa.split("");
    
        Map map =  Arrays.stream(stringarray)
            .collect(Collectors.groupingBy(c -> c , Collectors.counting()));
            map.forEach( (k, v) -> System.out.println(k + " : "+ v)        );
        }
    }
    

提交回复
热议问题