Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

Handling character counts within a string is common in various programming scenarios. One efficient approach is to utilize a HashMap to store the frequency of each character in the string.

In this tutorial, we’ll explore how to create a HashMap containing the character count of a given string in Java.

2. Using Traditional Looping

One of the simplest methods to create a HashMap with a string’s character count is traditional looping. In this approach, we iterate through each character in the string and update the count of each character in the HashMap accordingly.

Let’s see how this can be implemented:

String str = "abcaadcbcb";

@Test
public void givenString_whenUsingLooping_thenVerifyCounts() {
    Map<Character, Integer> charCount = new HashMap<>();
    for (char c : str.toCharArray()) {
        charCount.merge(c, 1, Integer::sum);
    }
    assertEquals(3, charCount.get('a').intValue());
}

In the test method, we first instantiate a map object named charCount that will hold the character counts. Afterward, we iterate over each character in the string str. For each character, we use the charCount.merge() method of the Map interface to update the count of occurrences in the charCount map.

If the character is encountered for the first time, we initialize its count to 1; otherwise, we increment the existing count by 1. Finally, we verify that the charCount map correctly stores the count of the character ‘a‘ as 3.

3. Using Java Streams

Alternatively, we can utilize Java Streams to achieve the same result with a more concise and functional approach. With Streams, we can easily group and count the occurrences of characters in the string. Here’s how we can implement it using Java Streams:

@Test
public void givenString_whenUsingStreams_thenVerifyCounts() {
    Map<Character, Integer> charCount = str.chars()
        .boxed()
        .collect(toMap(
          k -> (char) k.intValue(),
          v -> 1,
          Integer::sum));
    assertEquals(3, charCount.get('a').intValue());
}

Here, we first convert the str string into an IntStream using the chars() method. Next, each integer representing a Unicode code point is boxed into a Character object using the boxed() method, resulting in a Stream<Character>. Moreover, by employing the collect() method, we accumulate the stream elements into a Map<Character, Integer>.

The toMap() collector is crucial in mapping each character to its count. Within this collector, we define three parameters: a key mapper function that converts each character into a Character object; a value mapper function that assigns a count of 1 to each character encountered; and a merge function, Integer::sum, which aggregates the counts of characters with the same key by summing their values.

4. Conclusion

In this article, we created a HashMap with a string’s character count. Whether through traditional looping or utilizing Java Streams, the key is to efficiently iterate through the string’s characters and update the count in the HashMap.

As always, the complete code samples for this article can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Subscribe
Notify of
guest
1 Comment
Oldest
Newest
Inline Feedbacks
View all comments