This is the complete solution to find the duplicate words in a given sentence . This solution is designed to to solve the problem using an interface, super class and two derived classes implementing the interface.
package pack1;
public interface DuplicateIntf {
/* Define the functional interface with SAM 'DuplicateWordsCheck' */
void DuplicateWordsCheck(String str1);
/* Define the function which returns the duplicate status flag */
boolean fetchDuplicateStatusFlag();
/* Define the static method 'displayMsg' */
static void displayMsg(boolean trueOrFalse, String inpSen) {
if (trueOrFalse)
System.out.println("No Duplicate words found in '" + inpSen + "'\n");
}
}
package pack1;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;
class InputSentence {
private String[] strParam;
boolean noDuplicates = true;
/* Declare the logger object for the class to display the log messages */
static Logger logger = Logger.getLogger(InputSentence.class.getName());
public boolean validateInputs(String groupOfwords) {
/* Fetch the class object's name from which this method is called */
String cName = Thread.currentThread().getStackTrace()[2].getClassName();
String mName = "validateInputs()";
logger.info("This method '" + mName + "' called from the Class '" + cName + "'");
/* Validating the function parameters using Optional String data type methods */
Optional<String> strInput = Optional.ofNullable(groupOfwords);
/*
* Fetch the value of the Optional String parameters using 'isPresent' condition
* check. If the value is available use 'get' method otherwise simply return
* 'false' to stop the program execution without proceeding further.
*/
if (strInput.isPresent()) {
String[] words = groupOfwords.split("\\s+");
setStrParam(words);
} else {
setNoDuplicates(false);
return false;
}
logger.info("Input sentence is validated Successfully");
return true;
}
/* Define getter and setters for strParam & noDupliates flag variables */
public String[] getStrParam() {
return strParam;
}
public void setStrParam(String[] strings) {
this.strParam = strings;
}
public boolean isNoDuplicates() {
return noDuplicates;
}
public void setNoDuplicates(boolean noDuplicates) {
this.noDuplicates = noDuplicates;
}
}
class Duplicatewords_Using_String extends InputSentence implements DuplicateIntf {
public void DuplicateWordsCheck(String sentence) {
String repWords = "";
/* Fetch the class object's name from which this method is called */
String cName = Thread.currentThread().getStackTrace()[2].getClassName();
String mName = "DuplicateWordsCheck";
logger.info("This method '" + mName + "' called from the Class '" + cName + "'");
if (validateInputs(sentence)) {
System.out.println("The given input sentence is = '" + sentence + "'");
/*
* Traversing through the split words array using nested for loop and comparing
* each word with remaining words
*/
for (int i = 0; i < getStrParam().length; i++) {
for (int j = i + 1; j < getStrParam().length; j++) {
if (getStrParam()[i].contentEquals(getStrParam()[j])) {
/*
* Maintaining the repeated words string to avoid displaying the message every
* time when same word encounters
*/
setNoDuplicates(false);
if (!repWords.contains(getStrParam()[i])) {
repWords = repWords.concat(getStrParam()[i]).concat(" ");
System.out.println("The word=" + getStrParam()[i] + " is repeated\n");
continue;
}
}
}
}
DuplicateIntf.displayMsg(isNoDuplicates(), sentence);
} else
logger.info("The given Input sentence is null");
}
/* Fetch the duplicate flag status value */
public boolean fetchDuplicateStatusFlag() {
return isNoDuplicates();
}
}
class Duplicatewords_Using_Hashmap extends InputSentence implements DuplicateIntf {
public void DuplicateWordsCheck(String sentence) {
HashMap<String, Integer> wordsCnt = new HashMap<String, Integer>();
int idx = 0;
/* Fetch the class object's name from which this method is called */
String cName = Thread.currentThread().getStackTrace()[2].getClassName();
String mName = "DuplicateWordsCheck";
logger.info("This method '" + mName + "' called from the Class '" + cName + "'");
if (validateInputs(sentence)) {
System.out.println("The given input sentence is = '" + sentence + "'");
/*
* Traversing through the split words array using nested for loop and comparing
* each word with remaining words. Save each of the word from the given sentence
* into the HashMap
*/
while (getStrParam().length != idx) {
String nextWord = getStrParam()[idx++];
if (!wordsCnt.containsKey(nextWord))
wordsCnt.put(nextWord, 1);
else
wordsCnt.put(nextWord, wordsCnt.get(nextWord) + 1);
}
System.out.println("HashMap of words from the given input sentence");
System.out.println(wordsCnt);
/*
* Traversing the wordsCnt HashMap to check the occurrences of any word entry
* more than one time
*/
for (Entry<String, Integer> mapEntries : wordsCnt.entrySet())
if (mapEntries.getValue() > 1) {
System.out.println(
"The word=" + mapEntries.getKey() + " is repeated " + mapEntries.getValue() + " times\n");
setNoDuplicates(false);
}
DuplicateIntf.displayMsg(isNoDuplicates(), sentence);
} else
logger.info("The given Input sentence is null");
}
/* Fetch the duplicate flag status value */
public boolean fetchDuplicateStatusFlag() {
return isNoDuplicates();
}
}
class Duplicatewords_Using_Collection extends InputSentence implements DuplicateIntf {
public void DuplicateWordsCheck(String sentence) {
/* Fetch the class object's name from which this method is called */
String cName = Thread.currentThread().getStackTrace()[2].getClassName();
String mName = "DuplicateWordsCheck";
logger.info("This method '" + mName + "' called from the Class '" + cName + "'");
if (validateInputs(sentence)) {
System.out.println("The given input sentence is = '" + sentence + "'");
List<String> words = Arrays.asList(sentence.split(" "));
Set<String> IndividualWords = new HashSet<String>(words);
/*
* Traversing the words list for from each word in the IndividualWords set to
* check for more occurrences
*/
for (String eachWord : IndividualWords) {
if (Collections.frequency(words, eachWord) > 1) {
System.out.println("The word=" + eachWord + " repeated " + Collections.frequency(words, eachWord)
+ " times\n");
setNoDuplicates(false);
}
}
DuplicateIntf.displayMsg(isNoDuplicates(), sentence);
} else
logger.info("The given Input sentence is null");
}
/* Fetch the duplicate flag status value */
public boolean fetchDuplicateStatusFlag() {
return isNoDuplicates();
}
}
public class DuplicateWordsJ8 {
public static void main(String[] args) {
/*
* create the class object Duplicatewords_Using_String, and call the method
* DuplicateWordsCheck
*/
Duplicatewords_Using_String DWUStr = new Duplicatewords_Using_String();
DWUStr.DuplicateWordsCheck("Java python Java C#");
/*
* create the class object Duplicatewords_Using_Hashmap, and call the method
* DuplicateWordsCheck
*/
Duplicatewords_Using_Hashmap DWUHm = new Duplicatewords_Using_Hashmap();
DWUHm.DuplicateWordsCheck("Tomcat Jboss Weblogic");
/*
* create the class object Duplicatewords_Using_Collection, and call the method
* DuplicateWordsCheck
*/
Duplicatewords_Using_Collection DWUCf = new Duplicatewords_Using_Collection();
DWUCf.DuplicateWordsCheck("");
}
}
OUTPUT:
Jan 20, 2023 9:12:57 PM pack1.Duplicatewords_Using_String DuplicateWordsCheck
INFO: This method 'DuplicateWordsCheck' called from the Class 'pack1.DuplicateWordsJ8'
Jan 20, 2023 9:12:57 PM pack1.InputSentence validateInputs
INFO: This method 'validateInputs()' called from the Class 'pack1.Duplicatewords_Using_String'
Jan 20, 2023 9:12:57 PM pack1.InputSentence validateInputs
INFO: Input sentence is validated Successfully
The given input sentence is = 'Java python Java C#'
The word=Java is repeated
Jan 20, 2023 9:12:57 PM pack1.Duplicatewords_Using_Hashmap DuplicateWordsCheck
INFO: This method 'DuplicateWordsCheck' called from the Class 'pack1.DuplicateWordsJ8'
Jan 20, 2023 9:12:57 PM pack1.InputSentence validateInputs
INFO: This method 'validateInputs()' called from the Class 'pack1.Duplicatewords_Using_Hashmap'
Jan 20, 2023 9:12:57 PM pack1.InputSentence validateInputs
INFO: Input sentence is validated Successfully
The given input sentence is = 'Tomcat Jboss Weblogic'
HashMap of words from the given input sentence
{Tomcat=1, Jboss=1, Weblogic=1}
No Duplicate words found in 'Tomcat Jboss Weblogic'
Jan 20, 2023 9:12:57 PM pack1.Duplicatewords_Using_Collection DuplicateWordsCheck
INFO: This method 'DuplicateWordsCheck' called from the Class 'pack1.DuplicateWordsJ8'
Jan 20, 2023 9:12:57 PM pack1.InputSentence validateInputs
INFO: This method 'validateInputs()' called from the Class 'pack1.Duplicatewords_Using_Collection'
Jan 20, 2023 9:12:57 PM pack1.InputSentence validateInputs
INFO: Input sentence is validated Successfully
The given input sentence is = ''
No Duplicate words found in ''
The link to the JUnit5 test for this solution is here – https://atomic-temporary-185308886.wpcomstaging.com/2023/01/21/junit-test-duplicate-words/

Leave a comment