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 Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read