Find duplicate characters in a string and count its occurrences using Java 8

Navnath Jadhav
1 min readAug 1, 2022

--

Hello readers,

In this article, I'm sharing a way by which we can find occurrences of each character in a string that are duplicate.

1. We will use chars() the method of String returns us surrogate code point of each character in String

2 Using mapToObj we will map those code points to the character c -> (char) c

3 Using Collectors.groupingBy and Collectors.counting() we will calculate occurrences of each character in the string

4. After counting occurrences we want to keep only duplicate characters. Collectors.collectingAndThen() can help us to do some computation on the final result, It accepts the first parameter as a Collectors, so we will provide groupingBy as a first parameter and second parameter as a Function which accepts a result generated by groupingBy (Map<Character, Long>)and returns us a new Map ( Function<Map<Character, Long>, Map<Character, Long>>).

Using filter we will drop characters which are distinct and pass further only characters that occurred more than once filter(e -> e.getValue() > 1)

If you don’t want to preserve the order of character in a string then you can remove LinkedHashMap, So it will be like toMap(Map.Entry::getKey, Map.Entry::getValue) and groupingBy(c -> c, counting())

Demo

--

--