I have a HashMap
defined like this...
HashMap uniqueNames = new HashMap();
It stor
Most obvious, now allowing for multiple with largest occurrence value:
Integer largestVal = null;
List<Entry<String, Integer>> largestList = new ArrayList<Entry<String, Integer>>();
for (Entry<String, Integer> i : uniqueNames.entrySet()){
if (largestVal == null || largestVal < i.getValue()){
largestVal = i.getValue();
largestList .clear();
largestList .add(i);
}else if (largestVal == i.getValue()){
largestList .add(i);
}
}
Another option would be to use Guava's BiMap.
BiMap<String, Integer> uniqueNames = ...;
List<Integer> values = Lists.newArrayList(uniqueNames.values());
Collections.sort(values);
String name = uniqueNames.inverse().get(values.get(0));
This is my approach.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class FindWordCounter {
public static void main(String[] args) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter the sentence: ");
String sentence = bufferedReader.readLine();
FindWordCounter.countWord(sentence);
} catch (IOException e) {
System.out.println(e);
}
}
public static void countWord(String sentence) {
Map<String, Integer> hashMap = new HashMap<String, Integer>();
String[] word = sentence.toLowerCase().split(" ");
for (int i=0; i<word.length; i++) {
if (hashMap.containsKey(word[i])) {
int count = hashMap.get(word[i]);
hashMap.put(word[i], count + 1);
}
else {
hashMap.put(word[i], 1);
}
}
Entry<String,Integer> maxCount = null;
for(Entry<String,Integer> entry : hashMap.entrySet()) {
if (maxCount == null || entry.getValue() > maxCount.getValue()) {
maxCount = entry;
}
}
System.out.println("The word with maximum occurence is: " + maxCount.getKey()
+ " and the number of occurence is: " + maxCount.getValue());
}
}