English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
To find unique words in a string, use Java's Map utility because its properties are that it does not contain duplicate keys. To find unique words, first get all the words in the array for comparison. Space/second. If there are other characters, such as commas (,) or periods (.), these characters in the string should be replaced first using the required regular expression.
Insert each word in the string as the key of the Map, and provide the initial value corresponding to each key, which is 'Unique', if this word has not been inserted into the Map before. Repeat this process until all words in the string have been inserted and checked.
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 Result
{Guitar=Unique, is=Unique, instrument=Unique, and=Unique, Piano=Unique}