---
title: Find the frequency of character in a string
url: https://docs.vultr.com/java/examples/find-the-frequency-of-character-in-a-string
publish_date: 2024-12-03T14:00:00.873522Z
last_updated: 2024-12-03T14:00:00.873522Z
header_image: https://assets.vultrdevrel.com/docs-main-doc-assets-1/collection-items/1206/5dd679b2-d913-4c28-bee1-d4846cbbb114.jpg
---

> Index of every Vultr Docs page in markdown: https://docs.vultr.com/llms.txt

# Java Program to Find the Frequency of Character in a String

## Introduction
Finding the frequency of characters in a string is a common task in programming and data processing, which involves counting how many times each character appears in the string. This can help in various applications such as data validation, cryptography, and text analysis tasks. Java, with its robust standard libraries and string manipulation capabilities, provides efficient methods to accomplish this task.

In this article, you will learn how to determine the frequency of each character in a string using Java. The examples provided will enhance your understanding of string manipulation and character counting in Java, which are fundamental for solving more complex problems in software development.

## Using Character Counting with HashMap

### Explanation of the Method
1. Utilize a `HashMap` to store characters and their corresponding frequencies.
1. Iterate over each character in the string.
1. For each character, update its count in the `HashMap`.

### Example Code
1. Create a Java function to compute the frequency of each character.
1. Implement the function using a `HashMap`.

    ```java
    import java.util.HashMap;
    import java.util.Map;

    public class FrequencyFinder {
        public static void findFrequency(String str) {
            HashMap<Character, Integer> charCountMap = new HashMap<>();

            for (char c : str.toCharArray()) {
                if (charCountMap.containsKey(c)) {
                    charCountMap.put(c, charCountMap.get(c) + 1);
                } else {
                    charCountMap.put(c, 1);
                }
            }

            for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
                System.out.println(entry.getKey() + " " + entry.getValue());
            }
        }

        public static void main(String[] args) {
            findFrequency("hello");
        }
    }
    ```

1. This Java code initializes a `HashMap` called `charCountMap` to store the frequency of each character.
1. The `for` loop iterates over each character in the `str`, and the map is updated accordingly.
1. The second `for` loop prints each character and its frequency.

## Using Java 8 Stream API

### Explanation of the Method
1. Leverage the Stream API for a more concise and functional approach.
1. Convert the string into a stream of characters and collect frequencies in a `Map`.

### Example Code
1. Re-write the character frequency function using Java 8 features.

    ```java
    import java.util.stream.Collectors;
    import java.util.Map;
    import java.util.function.Function;

    public class FrequencyFinder {
        public static void findFrequencyWithStream(String str) {
            Map<Character, Long> charCountMap = str.chars()
                .mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

            charCountMap.forEach((key, value) -> System.out.println(key + " " + value));
        }

        public static void main(String[] args) {
            findFrequencyWithStream("hello");
        }
    }
    ```

1. The `chars()` method converts the String into an `IntStream`, which is then cast to a stream of `Character`.
1. The `collect()` method groups the stream by character, counting occurrences using `Collectors.counting()`.

## Conclusion
By mastering the frequency count of characters in a Java string either through a `HashMap` or using the Stream API, you enhance your ability to handle string data effectively. Both methods offer flexibility for different scenarios: the `HashMap` approach for traditional iterative solutions and the Stream API for a more functional style. Applying these techniques will undoubtedly lead to cleaner, more efficient Java code for various text processing tasks.