This is the second solution to find the maximum length and minimum length strings from a given input sentence of strings, using the HashMap methods.
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.StringTokenizer;
public class MinandMaxLengthStringsUsingHashmap {
public static void main(String args[]) {
@SuppressWarnings("resource")
Scanner inpStr=new Scanner(System.in);
HashMap<String, Integer> strCountMap = new HashMap<String, Integer>();
String sentence=inpStr.nextLine();
System.out.println("The given sentence is="+sentence);
StringTokenizer wordsOfsentence=new StringTokenizer(sentence);
//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());
}
System.out.println(strCountMap);
//Find the Max and Min Values from Hashmap KVPairs
int maxValue=Collections.max(strCountMap.values());
int 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)
System.out.println("The maximum Length String is="+mapEntry.getKey());
if (mapEntry.getValue()==minValue)
System.out.println("The minimum Length String is="+mapEntry.getKey());
}
}
}
OUTPUT:
This is really great interview
The given sentence is=This is really great interview
{This=4, is=2, great=5, interview=9, really=6}
The minimum Length String is=is
The maximum Length String is=interview

Leave a comment