Java Program to Print all Unique Words of a String
Last Updated :
17 Oct, 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 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
// 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);
}
}
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 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);
}
}
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
// 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);
}
}
}
}
Similar Reads
Java program to print Even length words in a String Given a string s, write a Java program to print all words with even length in the given string. Example to print even length words in a String Input: s = "i am Geeks for Geeks and a Geek" Output: am GeekExample:Java// Java program to print // even length words in a string class GfG { public static v
3 min read
Java Program to Search a Particular Word in a String Using Regex In Java string manipulation, searching for specific words is a fundamental task. Regular expressions (regex) offer a powerful and flexible approach to achieve this search. It matches the patterns simply by comparing substrings. In this article, we will learn how to search for a particular word in a
3 min read
Java Program to Find the Occurrence of Words in a String using HashMap HashMap<Key, Value> provides the basic implementation of the Map interface of Java and import java.util.HashMap package or its superclass. HashMap stores the data in (Key, Value) pairs, and accessed by an index of another type (e.g. an Integer). One object is used as a key to another object. I
3 min read
Java Program to Find Occurrence of a Word Using Regex Java's regular expressions, or regex, let you do advanced text manipulation and matching. Regex offers a handy approach for searching for a term in a text wherever it appears. In this article, we will learn to find every occurrence of a word using regex. Program to Find Occurrence of a Word Using Re
2 min read
Java program to print all duplicate characters in a string Given a string, the task is to write Java program to print all the duplicate characters with their frequency Example: Input: str = "geeksforgeeks" Output: s : 2 e : 4 g : 2 k : 2 Input: str = "java" Output: a : 2 Approach: The idea is to do hashing using HashMap. Create a hashMap of type {char, int}
2 min read