You can do it like this. Stream entrySet of the map and then get the maximum entry by using maxBy on the value of the entry. Since maxBy returns an Optional, you can then use map to get the value. Return an informatory message if no value exists.
String result = wordFreq.entrySet().stream()
.collect(Collectors.maxBy(Entry.comparingByValue()))
.map(Entry::getKey).orElse("No Value Found");
And as was commented on you could also do this. I tend to use the first one out of habit.
String result = wordFreq.entrySet().stream()
.max(Entry.comparingByValue())
.map(Entry::getKey).orElse("No Value Found");
You could also use other ways to optimize this but since you constructed a map I figured that is how you wanted to do it.
If you need a map of words, you may want to construct it outside of the method. Then just pass the map to the method instead of an array of sentences. That way you can use the map for other things.
Since you haven't yet had a chance to respond to my question, I will offer a solution regarding ties for the maximum occurrence of a word. Similar as before except first you return the maximum value found. The you can stream the entrySet, filtering for the entries that have the maximum value. Then just collect into a list.
int max = wordFreq.entrySet().stream()
.max(Entry.comparingByValue()).map(Entry::getValue)
.orElse(0);
List<String> wordFreq.entrySet().stream()
.filter(e -> e.getValue() == max).map(Entry::getKey)
.toList();
}
Lastly, you use stream constructs to create the initial frequency map. I am using \\s+ as the regex as there could be more than one space. The splitAsStream will apply the pattern and the toMap is similar to a merge in functionality.
Map<String, Integer> wordFreq = Arrays.stream(sentences)
.flatMap(s -> Pattern.compile("\\s+").splitAsStream(s))
.collect(Collectors.toMap(x -> x, x -> 1,
Integer::sum));