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
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.
Java 8 way:
"The quick brown fox jumped over the lazy dog."
.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(Object::toString, Collectors.counting()));
Finding the duplicates in a String
:
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
}
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) );
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With