- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to Print all unique words of a String
To find unique words in a string use Map utility of java because of its property that it does not contain duplicate keys.In order to find unique words first get all words in array so that compare each word,for this split string on the basis of space/s.If other characters such as comma(,) or fullstop (.) are present then using required regex first replace these characters from the string.
Insert each word of string as key of Map and provide initial value corresponding to each key as 'is unique' if this word does not inserted in map before.Now when a word repeats during insertion as key in Map delete its entry from map.Continue this for each word untill all words of string get check for insertion.
Example
import java.util.LinkedHashMap; import java.util.Map; public class Tester { public static void main(String[] args) { String str = "Guitar is instrument and Piano is instrument"; String[] strArray = str.split("\s+"); Map<String, String> hMap = new LinkedHashMap<String, String>(); for(int i = 0; i < strArray.length ; i++ ) { if(!hMap.containsKey(strArray[i])) { hMap.put(strArray[i],"Unique"); } } System.out.println(hMap); } }
Output
{Guitar=Unique, is=Unique, instrument=Unique, and=Unique, Piano=Unique}
- Related Articles
- C++ program to print unique words in a file
- Print all funny words in a string in C++
- Java Program to Print even length words
- Python program to print even length words in a string
- Java program to print unique values from a list
- Java Program to Print a String
- Print all permutations of a string in Java
- Python Program to print all permutations of a given string
- C Program to print all permutations of a given string
- Java Program to print distinct permutations of a string
- Program to print all substrings of a given string in C++
- Java program to count words in a given string
- Java Program to count the number of words in a String
- Python program to check if a string contains all unique characters
- C# program to determine if a string has all unique characters

Advertisements