Java Program to Print all Unique Words of a String

26 Apr, 2022
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:
Using nested loopsUsing Map
Using nested loops
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
Extract words from string using split() method and store them in an array.Iterate over the word array using for loop.Use another loop to find the occurrence of the current word the array.If the second occurrence is found increment count and set the word to “”If the count of the current word is equal to one print it
Extract words from string using split() method and store them in an array.
Iterate over the word array using for loop.
Use another loop to find the occurrence of the current word the array.
If the second occurrence is found increment count and set the word to “”
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 classpublic 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");         // Iterating 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);    }}
  
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 packageimport java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map; // Main classpublic class GFG {     // Method 1    // To print all unique words in the string    static void printUniqueWords(String str)    {        // Create a new Map by 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);    }}
  
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.
 
surinderdawra388
varshagumber28
Java-String-Programs
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array