This is the complete solution to find the Max and Min Length Strings from the 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 MinMaxLengthStrIntf {
/* Define the functional interface with SAM 'ParseEachWord' */
String ParseEachWord(String str1);
/* Define the static method 'displayMsg' */
static void displayMsg(String minLenStr, String maxLenStr) {
System.out.println("This Min Length String is '" + minLenStr + "'& the Max Length String is '" + maxLenStr + "'");
System.out.println("\n");
}
}
package pack1;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.StringTokenizer;
import java.util.logging.Logger;
class SentenceInput {
private String strParam;
/* Declare the logger object for the class to display the log messages */
static Logger logger = Logger.getLogger(SentenceInput.class.getName());
public boolean validateInputs(String inpSentence) {
/* 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(inpSentence);
/*
* 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()) {
setStrParam(strInput.get());
} else {
return false;
}
logger.info("The provided Input validated Successfully");
return true;
}
/* Define getter and setters for strParam variables */
public String getStrParam() {
return strParam;
}
public void setStrParam(String strings) {
this.strParam = strings;
}
}
class MinMaxLenghtString_Using_String extends SentenceInput implements MinMaxLengthStrIntf {
public String ParseEachWord(String inpSentence) {
/* Fetch the class object's name from which this method is called */
String cName = Thread.currentThread().getStackTrace()[2].getClassName();
String mName = "ParseEachWord";
logger.info("This method '" + mName + "' called from the Class '" + cName + "'");
String maxLenStr = null;
String minLenStr = null;
if (validateInputs(inpSentence)) {
System.out.println("The given input sentence is = '" + getStrParam() + "'");
/* Traversing through each word of the sentence, and then reverse each token */
StringTokenizer wordsOfsentence = new StringTokenizer(getStrParam());
/* Initialize the max and min variable */
int max = 0, min = inpSentence.length();
/*
* Process each word of the given sentence and check the length of each word
* against min and max variables
*/
while (wordsOfsentence.hasMoreTokens()) {
String eachWord = wordsOfsentence.nextToken();
if (eachWord.length() > max) {
max = eachWord.length();
maxLenStr = eachWord;
}
if (eachWord.length() < min) {
min = eachWord.length();
minLenStr = eachWord;
}
}
} else
logger.info("The given Input sentence is null");
MinMaxLengthStrIntf.displayMsg(minLenStr, maxLenStr);
return minLenStr + '#' + maxLenStr;
}
}
class MinMaxLenghtString_Using_Hashmap extends SentenceInput implements MinMaxLengthStrIntf {
public String ParseEachWord(String inpSentence) {
/* Fetch the class object's name from which this method is called */
String cName = Thread.currentThread().getStackTrace()[2].getClassName();
String mName = "ParseEachWord";
logger.info("This method '" + mName + "' called from the Class '" + cName + "'");
HashMap<String, Integer> strCountMap = new HashMap<String, Integer>();
String maxLenStr = null;
String minLenStr = null;
int maxValue = 0;
int minValue = 0;
if (validateInputs(inpSentence)) {
System.out.println("The given input sentence is = '" + getStrParam() + "'");
/* Traversing through each word of the sentence, and then reverse each token */
StringTokenizer wordsOfsentence = new StringTokenizer(getStrParam());
/*
* Process each word of the given sentence and check the length of each word
* against min and max variables
*/
while (wordsOfsentence.hasMoreTokens()) {
String eachWord = wordsOfsentence.nextToken();
if (!strCountMap.containsKey(eachWord))
strCountMap.put(eachWord, eachWord.length());
}
if (!strCountMap.isEmpty()) {
/* Find the Max and Min Values from Hashmap KVPairs */
maxValue = Collections.max(strCountMap.values());
minValue = Collections.min(strCountMap.values());
}
/*
* Traverse through each Hashmap entry, compare with Max and Min values and then
* print the respective Key values.
*/
for (Entry<String, Integer> mapEntry : strCountMap.entrySet()) {
if (mapEntry.getValue() == maxValue)
maxLenStr = mapEntry.getKey();
if (mapEntry.getValue() == minValue)
minLenStr = mapEntry.getKey();
}
} else
logger.info("The given Input sentence is null");
MinMaxLengthStrIntf.displayMsg(minLenStr, maxLenStr);
return minLenStr + '#' + maxLenStr;
}
}
class MinMaxLenghtString_Using_Stream extends SentenceInput implements MinMaxLengthStrIntf {
public String ParseEachWord(String inpSentence) {
/* Fetch the class object's name from which this method is called */
String cName = Thread.currentThread().getStackTrace()[2].getClassName();
String mName = "ParseEachWord";
logger.info("This method '" + mName + "' called from the Class '" + cName + "'");
String maxLenStr = null;
String minLenStr = null;
if (validateInputs(inpSentence)) {
System.out.println("The given input sentence is = '" + getStrParam() + "'");
/*
* Convert the given sentence into list of words using split, by providing one
* or more spaces regular expression
*/
ArrayList<String> arrWords = new ArrayList<>(Arrays.asList(getStrParam().split("\\s+")));
/*
* Use reduce() terminal method, and lambda expression with ternary operator, to
* find the largest string from the Arraylist of words.The final result of
* running the reducer across all elements of the array is a single value
*/
maxLenStr = arrWords.stream().reduce("", (s1, s2) -> s1.length() > s2.length() ? s1 : s2);
/*
* reduce() method works like Identity, Accumulator, and Combiner. The reduce()
* method executes a user-supplied callback function, which acts as reducer on
* each element of the array, in the order, passing in the return value from the
* calculation on the preceding element.
*/
minLenStr = arrWords.stream().reduce(inpSentence, (p1, p2) -> p1.length() < p2.length() ? p1 : p2);
} else
logger.info("The given Input sentence is null");
MinMaxLengthStrIntf.displayMsg(minLenStr, maxLenStr);
return minLenStr + '#' + maxLenStr;
}
}
public class MinMaxLengthStringJ8 {
public static void main(String args[]) {
/*
* create the class object MinMaxLenghtString_Using_String, and call the method
* ParseEachWord
*/
MinMaxLenghtString_Using_String MMLSUS = new MinMaxLenghtString_Using_String();
MMLSUS.ParseEachWord("Be like PRO Passion Resilience Optimisim");
MMLSUS.ParseEachWord(null);
/*
* create the class object MinMaxLenghtString_Using_Hashmap, and call the method
* ParseEachWord
*/
MinMaxLenghtString_Using_Hashmap MMLSUHM = new MinMaxLenghtString_Using_Hashmap();
MMLSUHM.ParseEachWord("Psychological time important over Linear time");
MMLSUHM.ParseEachWord(null);
/*
* create the class object MinMaxLenghtString_Using_Stream, and call the method
* ParseEachWord
*/
MinMaxLenghtString_Using_Stream MMLSUST = new MinMaxLenghtString_Using_Stream();
MMLSUST.ParseEachWord("Timing is always important than anything else");
MMLSUST.ParseEachWord(null);
}
}
OUTPUT:
Mar 04, 2023 8:22:21 PM pack1.MinMaxLenghtString_Using_String ParseEachWord
INFO: This method 'ParseEachWord' called from the Class 'pack1.MinMaxLengthStringJ8'
Mar 04, 2023 8:22:21 PM pack1.SentenceInput validateInputs
INFO: This method 'validateInputs()' called from the Class 'pack1.MinMaxLenghtString_Using_String'
Mar 04, 2023 8:22:21 PM pack1.SentenceInput validateInputs
INFO: The provided Input validated Successfully
The given input sentence is = 'Be like PRO Passion Resilience Optimisim'
This Min Length String is 'Be'& the Max Length String is 'Resilience'
Mar 04, 2023 8:22:21 PM pack1.MinMaxLenghtString_Using_String ParseEachWord
INFO: This method 'ParseEachWord' called from the Class 'pack1.MinMaxLengthStringJ8'
Mar 04, 2023 8:22:21 PM pack1.SentenceInput validateInputs
INFO: This method 'validateInputs()' called from the Class 'pack1.MinMaxLenghtString_Using_String'
Mar 04, 2023 8:22:21 PM pack1.MinMaxLenghtString_Using_String ParseEachWord
INFO: The given Input sentence is null
This Min Length String is 'null'& the Max Length String is 'null'
Mar 04, 2023 8:22:21 PM pack1.MinMaxLenghtString_Using_Hashmap ParseEachWord
INFO: This method 'ParseEachWord' called from the Class 'pack1.MinMaxLengthStringJ8'
Mar 04, 2023 8:22:21 PM pack1.SentenceInput validateInputs
INFO: This method 'validateInputs()' called from the Class 'pack1.MinMaxLenghtString_Using_Hashmap'
Mar 04, 2023 8:22:21 PM pack1.SentenceInput validateInputs
INFO: The provided Input validated Successfully
The given input sentence is = 'Psychological time important over Linear time'
This Min Length String is 'time'& the Max Length String is 'Psychological'
Mar 04, 2023 8:22:21 PM pack1.MinMaxLenghtString_Using_Hashmap ParseEachWord
INFO: This method 'ParseEachWord' called from the Class 'pack1.MinMaxLengthStringJ8'
Mar 04, 2023 8:22:21 PM pack1.SentenceInput validateInputs
INFO: This method 'validateInputs()' called from the Class 'pack1.MinMaxLenghtString_Using_Hashmap'
Mar 04, 2023 8:22:21 PM pack1.MinMaxLenghtString_Using_Hashmap ParseEachWord
INFO: The given Input sentence is null
This Min Length String is 'null'& the Max Length String is 'null'
Mar 04, 2023 8:22:21 PM pack1.MinMaxLenghtString_Using_Stream ParseEachWord
INFO: This method 'ParseEachWord' called from the Class 'pack1.MinMaxLengthStringJ8'
Mar 04, 2023 8:22:21 PM pack1.SentenceInput validateInputs
INFO: This method 'validateInputs()' called from the Class 'pack1.MinMaxLenghtString_Using_Stream'
Mar 04, 2023 8:22:21 PM pack1.SentenceInput validateInputs
INFO: The provided Input validated Successfully
The given input sentence is = 'Timing is always important than anything else'
This Min Length String is 'is'& the Max Length String is 'important'
Mar 04, 2023 8:22:21 PM pack1.MinMaxLenghtString_Using_Stream ParseEachWord
INFO: This method 'ParseEachWord' called from the Class 'pack1.MinMaxLengthStringJ8'
Mar 04, 2023 8:22:21 PM pack1.SentenceInput validateInputs
INFO: This method 'validateInputs()' called from the Class 'pack1.MinMaxLenghtString_Using_Stream'
Mar 04, 2023 8:22:21 PM pack1.MinMaxLenghtString_Using_Stream ParseEachWord
INFO: The given Input sentence is null
This Min Length String is 'null'& the Max Length String is 'null'
The link to the JUnit5 test for this solution is here – https://atomic-temporary-185308886.wpcomstaging.com/2023/03/05/junit-test-maxmin-length-of-strings/

Leave a comment