Java Program to Print all unique words of a String

Java 8Object Oriented ProgrammingProgramming

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

 Live Demo

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}
raja
Published on 01-Nov-2018 10:59:52
Advertisements