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 loops
- Using Map
- Using frequency() method of Collections
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
Example:
// 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" );
// 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 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 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.
Method 3 : Using Collections.frequency() . If the occurrence of word in string is 1 , then the word is unique.
// Java Program to Print all unique words // Main class import java.util.*;
public class Main{
public static void main(String[] args)
{
String str = "Welcome to geeks for geeks" ;
String[] words = str.split( "\\W" );
List<String> al = new ArrayList<>(Arrays.asList(words));
for (String x:al) {
if (Collections.frequency(al,x)== 1 ){
System.out.println(x);
}
}
}
} |
Welcome to for