How to Find Duplicate Words in String in Java

This is very common interview question where you have to find duplicate words in a string or text file. This can be solved using some overly-complex algorithms also, but in this post, I will propose rather an easy way using Java Collections API.

1. Problem

Lets say we have an String/ text like below-

“a r b k c d se f g a d f s s f d s ft gh f ws w f v x s g h d h j j k f sd j e wed a d f”;

Above string is the result of some random hits on keyboard to make it complete unpredictable. [For fun only :-)]

We will use Collections.frequency() method to do this job. This method seems to be here only for this purpose.

Lets go directly to our solution and see it works at all.

2. Java program to find repeated words

Given below is a Java program to find the number of occurrences of each word in a sentence or String.

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DuplicateWordSearcher {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {

		String text = "a r b k c d se f g a d f s s f d s ft gh f ws w f v x s g h d h j j k f sd j e wed a d f";

		List<String> list = Arrays.asList(text.split(" "));

		Set<String> uniqueWords = new HashSet<String>(list);
		for (String word : uniqueWords) {
			System.out.println(word + ": " + Collections.frequency(list, word));
		}
	}
}

Output:

ft: 1
f: 7
g: 2
d: 5
e: 1
b: 1
c: 1
a: 3
wed: 1
sd: 1
se: 1
j: 3
ws: 1
k: 2
h: 2
w: 1
v: 1
s: 4
r: 1
gh: 1
x: 1

3. Summary

In above example, we get a Java program to count how many times a word appears in a String or find duplicate words. It can help you in to find most frequent words or count repeated words in a string.

This can be a Java program to find unique words in a string, also. Just check the count which will be equal to one for unique words.

Happy Learning !!

Leave a Reply

30 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial