Java Program to Find Frequency of each Word in a String

In this section, we will show you three different ways to find frequency of each word in a given String in Java.

1. Using For loop and Map 

2. Using Java 8 Streams

3. Using Google Guava MultiSet

Example 1: Using For loop and Map 

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

public class Main {

public static void main(String[] args) {

String string = "Java Python Go C# Java Python Java Go C";

//Split the string into words based on whitespace
String words[] = string.split(" ");


Map<String, Integer> occurrences = new HashMap<>();

//Iterate through String array
for ( String word : words ) {

Integer oldCount = occurrences.get(word);
if ( oldCount == null ) {
oldCount = 0;
}
occurrences.put(word, oldCount + 1);
}

System.out.println(occurrences);
}
}

1. split() method in Java splits a string into substrings using a delimiter that is specified using a regular expression. Here delimiter is whitespace.

2. Then we iterate over String array and put the word and word count inside HashMap.

Console Output: 

{C#=1, Java=3, C=1, Go=2, Python=2}


Example 2: Using Java 8 Streams

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

public class Main {

public static void main(String[] args) {

String string = "Java Python Go C# Java Python Java Go C";

Map<String, Long> result =
Arrays.stream(string.split(" ")).collect(Collectors
.groupingBy(Function.identity(),Collectors.counting()));

System.out.println(result);
}
}

1. A Map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an entry. A Map contains unique keys.

2. stream() method accepts a mandatory parameter array which is the array of whose elements are to be converted into a sequential stream and returns a Sequential Stream from the array passed as the parameter.

3. Java Stream collect() performs a mutable reduction operation on the elements of the stream. This is a terminal operation.

4. The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed.

5. identity() is a static method of the Function interface that always returns the input argument.

6. Collectors counting() method is used to count the number of elements passed in the stream as the parameter. It returns a Collector accepting elements of type T that count the number of input elements. If no elements are present, the result is 0. It is a terminal operation.

Console Output: 

{C#=1, Java=3, C=1, Go=2, Python=2}


Example 3. Using Google Guava MultiSet

First add Google Guava to your project: https://mvnrepository.com/artifact/com.google.guava/guava
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;

public class Main {

public static void main(String[] args) {

String string = "Java Python Go C# Java Python Java Go C";
String []words = string.split(" ");

Multiset<String> frequencies = HashMultiset.create();
for (String word : words) {
frequencies.add(word);
}

for (String word : frequencies.elementSet()) {
System.out.println(word + " =>" + frequencies.count(word) );
}

}
}

A Multiset is an collection that is kindred to Set, but it may have duplicate elements. The duplicate elements are fortified by maintaining a count of the total number of times an element appears in the collection.

Console Output: 

C# =>1

Java =>3

C =>1

Go =>2

Python =>2

More Interesting topics,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete