Java Program to Count the Occurrences of Each Character in String | Java Inspires



Java Program to Count the Occurrences of Each Character in String
Java Program to Count the Occurrences of Each Character in String




In this post, we will write a simple java program to count the occurrences of each character in a given string.

Here, first we will take a string and then create a character stream by spliting with "", and collect each character and count by grouping using java 8 stream features.

package com.javainspires.examples;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ExampleMain {

    public static void main(String[] args) {
        
        String name = "Java Inspires Java Inspires";

        Map<String, Long> result = Arrays.stream(name.split(""))
                .collect(
                        Collectors.groupingBy(Function.identity(), Collectors.counting()));
        System.out.println(result);
    }
}

Output:

{p=2,  =3, a=4, r=2, s=4, e=2, v=2, i=2, I=2, J=2, n=2}




Search terms:

Java8: Create HashMap with character count of a String



Post a Comment

Previous Post Next Post