Skip to content
Related Articles

Related Articles

Improve Article

Java Program to Print all Unique Words of a String

  • Difficulty Level : Basic
  • Last Updated : 13 Sep, 2021
Geek Week

Java program to print all unique words present in the string. The task is to print all words occurring only once in the string.

Illustration:

Input  : Welcome to Geeks for Geeks.
Output : Welcome 
         to
         for
Input  : Java is great.Python is also great.
Output : Java
         Python
         also

Methods: 

This can be done in the following ways:

  1. Using nested loops
  2. Using Map

Naive approach: Using nested loops



The idea to count the occurrence of the string in the string and print if count equals one

  1. Extract words from string using split() method and store them in an array.
  2. Iterate over the word array using for loop.
  3. Use another loop to find the occurrence of the current word the array.
  4. If the second occurrence is found increment count and set the word to “”
  5. If the count of the current word is equal to one print it

Example:

Java




// Java Program to Print all unique words
// Using nested loops
 
// Main class
public class GFG {
 
    // Method 1
    // To print the unique words
    static void printUniqueWords(String str)
    {
        // Maintaining a count variable
        int count;
 
        // Extract words from string
        // using split() method
        String[] words = str.split("\\W");
 
        // Iteratating over the words array
        for (int i = 0; i < words.length; i++) {
 
            // Setting count of current word to one
            count = 1;
 
            for (int j = i + 1; j < words.length; j++) {
                if (words[i].equalsIgnoreCase(words[j])) {
 
                    // If word found later in array
                    // increment the count variable
                    count++;
 
                    words[j] = "";
                }
            }
 
            // If count of current word is one print it
            if (count == 1 && words[i] != "")
 
                // Print statement
                System.out.println(words[i]);
        }
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String str = "Welcome to geeks for geeks";
 
        // Calling the method 1 to print all unique words
        // in above string passed as argument
        printUniqueWords(str);
    }
}

 
 

Output
Welcome
to
for

Note: Time complexity is of order n^2 where space complexity is of order n

 

Method 2: Using Map

 



Approach: 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.

 

  • Create an empty Map.
  • Extract words from string using split() method and store them in an array.
  • Iterate over the word array.
  • Check if the word is already present in the Map or not.
  • If a word is present in the map, increment its value by one.
  • Else store the word as the key inside the map with value one.
  • Iterate over the map and print words whose value is equal to one.

 

Example:

 

Java




// Java Program to Print all Unique Words
// Using Map
 
// Importing utility classes from java.util package
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
 
// Main class
public class GFG {
 
    // Method 1
    // To print all unique words in the string
    static void printUniqueWords(String str)
    {
        // Create a new Map ny creating object of HashMap
        // class
        HashMap<String, Integer> map
            = new LinkedHashMap<String, Integer>();
 
        // Extract words from string
        // using split() method
        String[] words = str.split("\\W");
 
        // Iterating over the words array
        // using for each loop
        for (String word : words) {
 
            // If the word is present in array then
            //
            if (map.containsKey(word)) {
 
                //  Increment its value by one
                // using map.get() method
                map.put(word, map.get(word) + 1);
            }
 
            // Else store the word inside map
            // with value one
            else
                map.put(word, 1);
        }
 
        // Iterate over the map using for each loop
        for (Map.Entry<String, Integer> entry :
             map.entrySet()) {
 
            // If value of words equals unity
            if (entry.getValue() == 1)
 
                // Print all those words
                System.out.println(entry.getKey());
        }
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String str = "Welcome to geeks for geeks";
 
        // Calling the Method1 to
        // print all unique words in above string
        printUniqueWords(str);
    }
}

 
 

Output
Welcome
to
for

 

Note: Time complexity is of the order of n where space complexity is of order n. Hence, it is the optimal approach.

 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :