Java 8 – Count and print number of repeated character occurrences in a String

In this article, we will count and print number of repeated character occurrences in a String i.e.;

Counting & Printing duplicate character occurrences:

  • Using Java 8 Stream and Collectors
  • Using Java 8‘s Map.compute() method

1. Using Java 8 Stream and Collectors class

CountRepeatedCharactersUsingJava8.java

package in.bench.resources.count.lines.words;

import java.util.Comparator;
import java.util.Map;
import java.util.stream.Collectors;

public class CountRepeatedCharactersUsingJava8 {

	public static void main(String[] args) {

		// sample test string
		String input = "Spring and Hibernate and Web Services";


		// count repeated characters
		Map<Character, Long> characterCountMap = input
				.chars() // convert to IntStream
				.mapToObj(c -> (char) c) // map to Character object
				.filter(ch -> !Character.isWhitespace(ch))
				.collect(Collectors.groupingBy(ch -> ch, Collectors.counting()));


		// print to the console
		System.out.println("1. Characters and its Count in Random-order :- \n");
		characterCountMap
		.entrySet()
		.forEach(System.out::println);


		// print to the console
		System.out.println("\n\n2. Characters and its Count in Descending-order :- \n");
		characterCountMap
		.entrySet()
		.stream()
		.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
		.forEach(System.out::println);


		// count repeated characters IGNORING cases
		Map<Character, Long> ignoreCharacterCaseCountMap = input
				.chars() // convert to IntStream
				.mapToObj(ch -> (char) Character.toLowerCase(ch)) // map to Character object
				.filter(ch -> !Character.isWhitespace(ch))
				.collect(Collectors.groupingBy(ch -> ch, Collectors.counting()));


		// print to the console
		System.out.println("\n\n3. Characters and its Count in Ascending-order, "
				+ "ignoring cases :- \n");
		ignoreCharacterCaseCountMap
		.entrySet()
		.stream()
		.sorted(Map.Entry.comparingByValue())
		.forEach(System.out::println);
	}
}

Output:

1. Characters and its Count in Random-order :- 

a=3
b=2
c=1
d=2
e=5
g=1
H=1
i=3
n=4
p=1
r=3
s=1
S=2
t=1
v=1
W=1


2. Characters and its Count in Descending-order :- 

e=5
n=4
a=3
i=3
r=3
b=2
d=2
S=2
c=1
g=1
H=1
p=1
s=1
t=1
v=1
W=1


3. Characters and its Count in Ascending-order, ignoring cases :- 

c=1
g=1
h=1
p=1
t=1
v=1
w=1
b=2
d=2
a=3
i=3
r=3
s=3
n=4
e=5

2. Using Java 8’s Map.compute() method

  • Initially, we got a String “Spring and Hibernate and Web Services
  • Convert String into char[] array using toCharArray() method and at the same time replace all spaces
  • Create LinkedHashMap object and put each characters read from char[] array into Map using compute() method
  • While putting into Map, check if characters is already present,
    • If present, then increment value by 1
    • Otherwise 1

CountRepeatedCharactersUsingJava8MapCompute.java

package in.bench.resources.count.lines.words;

import java.util.LinkedHashMap;
import java.util.Map;

public class CountRepeatedCharactersUsingJava8MapCompute {

	public static void main(String[] args) {

		// sample test string
		String input = "Spring and Hibernate and Web Services";


		// convert String to char[] array replacing all space characters
		char[] chArray = input.replaceAll(" ", "").toCharArray();


		// count repeated characters
		Map<Character, Long> characterCountMap = new LinkedHashMap<>();


		// iterate char[] array and compute using Map
		for(int index=0; index < chArray.length; index++) {

			// check
			characterCountMap.compute(chArray[index], 
					(key, value) -> (value == null) ? 1 : value + 1);
		}


		// print to the console
		System.out.println("1. Characters and its Count in Random-order :- \n");
		characterCountMap
		.entrySet()
		.forEach(System.out::println);


		// print to the console
		System.out.println("\n\n2. Characters and its Count in Ascending-order :- \n");
		characterCountMap
		.entrySet()
		.stream()
		.sorted(Map.Entry.comparingByValue())
		.forEach(System.out::println);
	}
}

Output:

1. Characters and its Count in Random-order :- 

S=2
p=1
r=3
i=3
n=4
g=1
a=3
d=2
H=1
b=2
e=5
t=1
W=1
v=1
c=1
s=1


2. Characters and its Count in Ascending-order :- 

p=1
g=1
H=1
t=1
W=1
v=1
c=1
s=1
S=2
d=2
b=2
r=3
i=3
a=3
n=4
e=5

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 - Reverse each words in a String using Stream and Collectors
Java 8 – Count and print number of repeated word occurrences in a text file