Print all unique words of a String


Write a function that takes a String as argument and prints all unique words in it.


Input : Java is great. Grails is also great
Output : Java

The idea is to use map to keep track of words already occurred. But first we have to extract all words from a String, as a string may contain many sentences with punctuation marks.

For extracting words from a String, refer Extracting each word from a String.

// Java program to print unique words
// from a string

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test 
    // Prints unique words in a string
    static void printUniquedWords(String str)
        // Extracting words from string
        Pattern p = Pattern.compile("[a-zA-Z]+");
        Matcher m = p.matcher(str);
        // Map to store count of a word
        HashMap<String, Integer> hm = new HashMap<>();
        // if a word found
        while (m.find()) 
            String word =;
            // If this is first occurrence of word
                hm.put(word, 1);
                // increment counter of word
                hm.put(word, hm.get(word) + 1);
        // Traverse map and print all words whose count
        // is  1
        Set<String> s = hm.keySet();
        Iterator<String> itr = s.iterator();

            String w =;
            if (hm.get(w) == 1)
    // Driver Method
    public static void main(String[] args) 
        String str = "Java is great. Grails is also great";



This article is contributed by Gaurav Ahirwar and Gaurav Miglani . If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at to report any issue with the above content.

Recommended Posts:

1 Average Difficulty : 1/5.0
Based on 1 vote(s)

Writing code in comment? Please use, generate link and share the link here.