Java – Find Unique Words in a String

To find unique words in a Java string, split the text into words and store the words in a collection that does not keep duplicates. A HashSet is a simple choice when you need distinct words. A List with nested loops can also remove repeated values, although it requires more comparisons.

In this tutorial, we shall write Java programs to find the unique words in a given string. We will also look at whitespace, case sensitivity, punctuation, output order, and how to count the number of distinct words.

What Does “Unique Words” Mean in Java?

In this tutorial, unique words means the distinct word values in the string: each different word appears once in the result, even if it occurs several times in the input. For example, the string apple banana apple has two distinct words: apple and banana.

This is different from finding words that occur exactly once. If you need words that appear only one time, you must count the frequency of each word and keep only those whose count is 1.

Find Unique Words in String using HashSet

HashSet stores no duplicate values. When all words from the string are added to a HashSet, repeated words are automatically represented by a single set entry.

  1. Start.
  2. Read the input string.
  3. Split string with a delimiter. In the basic example below, the delimiter is a single space. This returns an array of words.
  4. Create a HashSet from the array of words. Repeated word values are removed by the set.
  5. Iterate over the set and print each distinct word.
  6. Stop.

In the following program, we just initialized a string str. You may load this variable with text from a file, or input read from user.

Example.java

</>
Copy
import java.util.Arrays;
import java.util.HashSet;

/**
 * Java Program - Find Unique Words
 */
public class Example {

	public static void main(String[] args) {

		String str = "apple banana mango grape lichi mango apple grape";
		
		String[] words = str.split(" ");
		
		HashSet<String> uniqueWords = new HashSet<String>(Arrays.asList(words));
		
		for(String s:uniqueWords)
			System.out.println(s);
	}

}

Output

banana
apple
lichi
grape
mango

A HashSet does not guarantee the order in which its elements are iterated. Therefore, the same unique words may be printed in a different order on another run or Java implementation. Use LinkedHashSet when the first-occurrence order matters.

Find Unique Words in String using List & Nested For Loop

Follow these steps to store unique words of a string in a List.

  1. Start.
  2. Read the input string.
  3. Split the string based on a delimiter. This can be a space, comma, or another separator appropriate for the input. This returns an array of words.
  4. Create a List from the array of words.
  5. For each word, compare it with the earlier words in the list. If the same value already exists, remove the later duplicate.
  6. After all comparisons, the list contains one occurrence of each distinct word.
  7. Stop.

In the following program, we used For Loop for iterating over the words in list.

Example.java

</>
Copy
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * Java Program - Find Unique Words
 */
public class Example {

	public static void main(String[] args) {

		String str = "apple banana banana mango grape lichi mango apple grape";
		
		String[] words = str.split(" ");
		
		List<String> uniqueWords = new ArrayList<String>(Arrays.asList(words));
		
		for(int i=1; i<uniqueWords.size(); i++) {
			for(int j=0;j<i;j++) {
				if(uniqueWords.get(i).equals(uniqueWords.get(j))) {
					uniqueWords.remove(i);
					i--;
					break;
				}
			}
		}
		
		for(String s: uniqueWords) {
			System.out.println(s);
		}
	}

}

Output

apple
banana
mango
grape
lichi

This approach keeps the first occurrence of each word in the list. It is useful for understanding the duplicate-removal logic, but the nested loops can make many comparisons as the number of words grows.

Preserve Unique Word Order with LinkedHashSet

If you want each distinct word once and also want to keep the order in which words first appear, use LinkedHashSet. The following example also uses split("\\s+") so that one or more whitespace characters can separate words.

</>
Copy
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

public class Example {
    public static void main(String[] args) {
        String str = "apple   banana apple\tmango banana";

        String[] words = str.trim().split("\\s+");
        Set<String> uniqueWords =
                new LinkedHashSet<>(Arrays.asList(words));

        for (String word : uniqueWords) {
            System.out.println(word);
        }
    }
}

Output

apple
banana
mango

Split a Java String on Multiple Spaces and Whitespace

The expression str.split(" ") splits only at a single space character. If the input may contain repeated spaces, tabs, or line breaks, a whitespace regular expression is more reliable.

</>
Copy
String[] words = str.trim().split("\\s+");

Here, \\s+ means one or more whitespace characters. Calling trim() first avoids an empty word caused by whitespace at the beginning or end of a non-empty string.

Find Unique Words Without Treating Uppercase and Lowercase as Different

Java string comparison is case-sensitive. Therefore, Apple and apple are different values in a set. If they should count as the same word, normalize the text before splitting it.

</>
Copy
import java.util.Arrays;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

public class Example {
    public static void main(String[] args) {
        String str = "Apple apple BANANA banana Mango";

        String[] words = str.toLowerCase(Locale.ROOT)
                            .trim()
                            .split("\\s+");

        Set<String> uniqueWords =
                new HashSet<>(Arrays.asList(words));

        System.out.println(uniqueWords);
    }
}

The result contains one set entry for each word regardless of capitalization. Since this example uses HashSet, the displayed order is not guaranteed.

Handle Punctuation Before Finding Unique Words

Splitting only on whitespace leaves punctuation attached to words. For example, apple and apple, would be different strings. If punctuation should not be part of a word, normalize it before splitting.

</>
Copy
String cleaned = str.toLowerCase(Locale.ROOT)
                    .replaceAll("[^\\p{L}\\p{N}']+", " ")
                    .trim();

String[] words = cleaned.isEmpty()
        ? new String[0]
        : cleaned.split("\\s+");

This example keeps Unicode letters, digits, and apostrophes, while replacing other runs of characters with spaces. The exact normalization rule should match what your application considers a word.

Count the Number of Unique Words in a Java String

After the words are stored in a set, use size() to get the number of distinct words.

</>
Copy
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Example {
    public static void main(String[] args) {
        String str = "apple banana apple mango banana";

        String[] words = str.trim().split("\\s+");
        Set<String> uniqueWords =
                new HashSet<>(Arrays.asList(words));

        System.out.println("Unique word count: " + uniqueWords.size());
    }
}

Output

Unique word count: 3

Find Words That Occur Exactly Once

If by “unique” you mean words that appear only once in the original string, a set alone is not enough because it removes duplicates without keeping their frequencies. Count each word first, then print only words with a count of 1.

</>
Copy
import java.util.LinkedHashMap;
import java.util.Map;

public class Example {
    public static void main(String[] args) {
        String str = "apple banana apple mango grape banana";

        Map<String, Integer> counts = new LinkedHashMap<>();

        for (String word : str.trim().split("\\s+")) {
            counts.put(word, counts.getOrDefault(word, 0) + 1);
        }

        for (Map.Entry<String, Integer> entry : counts.entrySet()) {
            if (entry.getValue() == 1) {
                System.out.println(entry.getKey());
            }
        }
    }
}

Output

mango
grape

HashSet or Nested Loop for Unique Words?

  • Use HashSet when you need distinct words and do not need to preserve their original order.
  • Use LinkedHashSet when you need distinct words in first-occurrence order.
  • Use a nested-loop solution mainly when you want to practice the duplicate-checking logic without relying on a set.
  • Use a frequency map when “unique” means words that occur exactly once.

Java Unique Words Tutorial Summary

In this Java Tutorial, we learned how to find unique words in a string using HashSet or a combination of List and nested for loops. We also saw how LinkedHashSet preserves first-occurrence order, how split("\\s+") handles general whitespace, how case and punctuation affect uniqueness, how to count distinct words, and how to find words that occur exactly once.