Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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 outputs are below,

'a' = 1
'o' = 4
'space' = 8
'.' = 1
like image 740
Praveenkumar_V Avatar asked Oct 29 '12 10:10

Praveenkumar_V


People also ask

How do I count the number of repeated characters in a string in Java 8?

first, we will take a character from string and place the current char as key and value will be 1 in the map. Next, take the second character. If the char is already present in the map using containsKey() method, then simply increase the current value by 1. Repeat the same for each character.


2 Answers

Java 8 way:

"The quick brown fox jumped over the lazy dog."
        .chars()
        .mapToObj(i -> (char) i)
        .collect(Collectors.groupingBy(Object::toString, Collectors.counting()));
like image 162
m190 Avatar answered Oct 22 '22 00:10

m190


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<Character ,Integer> map = new HashMap<>();
        for (int i = 0; i <a.length() ; i++ ) {
        char ch = a.charAt(i);
                map.put(ch , map.getOrDefault(ch,0) +1 );
        }//for

       List<Character> list = new ArrayList<>();
       Set<Map.Entry<Character ,Integer> > entrySet = map.entrySet();

       for (  Map.Entry<Character ,Integer> 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<String , Long> map =  Arrays.stream(stringarray)
        .collect(Collectors.groupingBy(c -> c , Collectors.counting()));
        map.forEach( (k, v) -> System.out.println(k + " : "+ v)        );
    }
}
like image 25
Soudipta Dutta Avatar answered Oct 22 '22 01:10

Soudipta Dutta