Java – Find Unique Words in a String
To find unique words in a string, split the string into words with a delimiter, and then from the words get those which are unique using a HashSet or a nested loop.
In this tutorial, we shall write Java programs to find the unique words in a given string.
Find Unique Words in String using HashSet
HashSet stores only unique values. Follow these steps to store unique words of a string in a HashSet.
- Start.
- Read input string.
- Split string with a delimiter, which is usually a single space. This returns an array of words.
- Create an Hashset with the array of words. Now, HashSet contains only unique words.
- You may print the unique words.
- Stop.
In the following program, we just initialized a string str
. You may load this variable with text from a file, or input read from user.
Example.java
import java.util.Arrays;
import java.util.HashSet;
/**
* Java Program - Find Unique Words
*/
public class Example {
public static void main(String[] args) {
String str = "apple banana mango grape lichi mango apple grape";
String[] words = str.split(" ");
HashSet<String> uniqueWords = new HashSet<String>(Arrays.asList(words));
for(String s:uniqueWords)
System.out.println(s);
}
}
Output
banana
apple
lichi
grape
mango
Find Unique Words in String using List & Nested For Loop
Follow these steps to store unique words of a string in a List.
- Start.
- Read input string.
- Split the string based on a delimiter. This can be a space, comma, or something that separates words in the string. This returns array or words.
- Create an List with the array of words.
- For each word in the list, check if there is another word with the same value. If so, delete the another word.
- At the end of all iterations, you end up with list containing only unique words.
- Stop.
In the following program, we used For Loop for iterating over the words in list.
Example.java
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Java Program - Find Unique Words
*/
public class Example {
public static void main(String[] args) {
String str = "apple banana banana mango grape lichi mango apple grape";
String[] words = str.split(" ");
List<String> uniqueWords = new ArrayList<String>(Arrays.asList(words));
for(int i=1; i<uniqueWords.size(); i++) {
for(int j=0;j<i;j++) {
if(uniqueWords.get(i).equals(uniqueWords.get(j))) {
uniqueWords.remove(i);
i--;
break;
}
}
}
for(String s: uniqueWords) {
System.out.println(s);
}
}
}
Output
apple
banana
mango
grape
lichi
Conclusion
In this Java Tutorial, we learned how to find unique words in a string, using HashSet or with the combination of List and nested for loop.