How to count frequency of a string in java using stream ?

--

In this tutorial we will use java 8 stream to find frequency of each character in a given String.

Count frequency of each character in a given String

Step 1: Split the input string to get each letters using input.split(“”)

Step 2: using the terminal operator collect and Collectors.groupingBy(Function.identity, counting()) we’ll reduce the stream to a Map with key as String and frequency as Long.

import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;

import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;

public class Test {
public static void main(String[] args) {
String input = "gain java knowledge";
Map<String, Long> countMap = Arrays.stream(input.split("")).collect(groupingBy(Function.identity(), counting()));
System.out.println(countMap);
}
}

--

--

Gain Java Knowledge

The Java programming language is one of the most popular languages today. Stay up to date with news, certifications, free learning resources and much more.