Write a java program to find the most repeated word in a string and also print its frequency.
INPUT
are you are
OUTPUT
are: 2
This question can be done by using HashMap or file reader (I suppose) but actually, I haven’t learned them yet.
Yet, I managed to write a code that displays the frequency (but not the word)
import java.util.Scanner;
class duplicatewords
{
void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
String str=sc.nextLine();
String arr[]=str.split(" ");
int count=1; int checkvalue=0;
for(int i=0;i<arr.length-1;i++)
{
String temp=arr[i];
for(int j=i+1;j<arr.length;j++)
{
String anothertemp=arr[j];
if(temp.equalsIgnoreCase(anothertemp))
count++;
}
if(checkvalue<c)
checkvalue=c;
c=1;
}
System.out.println(checkvalue);
}
}
I want to know how to print the word also without using any map or reader.
I think the program will be a very complicated one but I will understand.
Any help will be greatly appreciated.
>Solution :
Here is my solution using 2 arrays:
public static void main(String[] args) {
String input = "are you are";
String[] words = input.split(" ");
//the 10 is the limit of individual words:
String[] wordsBucket = new String[10];
Integer[] countBucket = new Integer[10];
for(String word:words){
int index = findIndex(word, wordsBucket);
incrementIndex(countBucket, index);
}
int highest = findMax(countBucket);
System.out.println(wordsBucket[highest]+": "+countBucket[highest]);
}
private static int findMax(Integer[] countBucket) {
int max = 0;
int maxIndex = 0;
for(int i=0;i<countBucket.length;i++) {
if(countBucket[i]==null) {
break;
}
if(countBucket[i] > max) {
max = countBucket[i];
maxIndex = i;
}
}
return maxIndex;
}
private static int findIndex(String word, String[] wordsBucket) {
for(int i=0;i<wordsBucket.length;i++) {
if(word.equals(wordsBucket[i])) {
return i;
}
if(wordsBucket[i] == null) {
wordsBucket[i] = word;
return i;
}
}
return -1;
}
private static void incrementIndex(Integer[] countBucket, int index) {
if(countBucket[index] == null){
countBucket[index] = 1;
} else {
countBucket[index]++;
}
}
This prints are: 2. As @knittl pointed out in the comments this can also be done with 1 array of Pair<String, Integer> or something similar.
If you are allowed to use Maps and streams, then this works too (using the same String[] words as input as above):
Map<String, Integer> countingMap = new HashMap<>();
Arrays.stream(words).forEach(w->countingMap.compute(w, (ww,c)->c==null?1:c+1));
Map.Entry<String, Integer> h = countingMap.entrySet().stream().sorted(Comparator.comparingInt(Map.Entry<String,Integer>::getValue).reversed()).findFirst().get();
System.out.println(h);
This prints are=2