patternjavaMinor
Occurrence of a word in a sentence
Viewed 0 times
wordsentenceoccurrence
Problem
I have written Java code that finds the frequency of the occurrence of a word in a sentence. It is working fine. The only thing I want to do is to optimize this code.
String str = "I am a Boy I am a";
String[] splitStr = str.split(" ");
int count = 0;
List list = new ArrayList<>();
for(String s:splitStr){
if(!list.contains(s)){
list.add(s);
}
}
for(int i=0;i<list.size();i++){
for(int j=0;j<splitStr.length;j++){
if(list.get(i).equals(splitStr[j])){
count++;
}
}
System.out.println("Occurrence of " + list.get(i) + " is " + count + " times.");
count=0;
}Solution
You can simplify your code to a great extent by using a
You can modify your code like so:
And then simply iterate over the map, and print the key: value pair:
Map instead of List. The map would store the mapping from each word to it's count in the array. You can modify your code like so:
String str = "I am a Boy I am a";
String[] splitStr = str.split(" ");
Map wordCount = new HashMap<>();
for (String word: splitStr) {
if (wordCount.containsKey(word)) {
// Map already contains the word key. Just increment it's count by 1
wordCount.put(word, wordCount.get(word) + 1);
} else {
// Map doesn't have mapping for word. Add one with count = 1
wordCount.put(word, 1);
}
}And then simply iterate over the map, and print the key: value pair:
for (Entry entry: map.entrySet()) {
System.out.println("Count of : " + entry.getKey() +
" in sentence = " + entry.getValue());
}Code Snippets
String str = "I am a Boy I am a";
String[] splitStr = str.split(" ");
Map<String, Integer> wordCount = new HashMap<>();
for (String word: splitStr) {
if (wordCount.containsKey(word)) {
// Map already contains the word key. Just increment it's count by 1
wordCount.put(word, wordCount.get(word) + 1);
} else {
// Map doesn't have mapping for word. Add one with count = 1
wordCount.put(word, 1);
}
}for (Entry<String, Integer> entry: map.entrySet()) {
System.out.println("Count of : " + entry.getKey() +
" in sentence = " + entry.getValue());
}Context
StackExchange Code Review Q#31440, answer score: 9
Revisions (0)
No revisions yet.