Reputation: 533
I have a program, which users can enter a sentence, and it can split each word into an array. Also, I need to count the frequency of each words. For example, Apple is an apple is a phone, the result is that Apple-1; is-2; an-1; a-1; phone-1.
Please help me solve this problem, I don't know how to count the frequency of each word.
Here is my code:
public static void main(String[] args)
{
while (true)
{
System.out.println("Enter a sentence:");
Scanner keyboard = new Scanner(System.in);
String sentence = keyboard.nextLine();
if (sentence.isEmpty()) // quit the program when user enter an empty string
{
break;
}
else
{
StringTokenizer st = new StringTokenizer(sentence);
List<String> sentenceElement = new ArrayList<String>();
while (st.hasMoreTokens())
{
sentenceElement.add(st.nextToken());
}
System.out.println(sentenceElement);
}
}
Thank you so much!!
Upvotes: 2
Views: 6921
Reputation: 513
After getting the string array you can try the following code from Java 10 onwards. It uses streams to get the frequency map.
import java.util.Arrays;
import java.util.stream.Collectors;
public class StringFrequencyMap {
public static void main(String... args) {
String[] wordArray = {"Apple", "is", "an", "apple", "is", "a", "phone"};
var freqCaseSensitive = Arrays.stream(wordArray)
.collect(Collectors.groupingBy(x -> x, Collectors.counting()));
//If you want case insensitive then use
var freqCaseInSensitive = Arrays.stream(wordArray)
.collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting()));
System.out.println(freqCaseSensitive);
System.out.println(freqCaseInSensitive);
}
}
Output:
{a=1, apple=1, Apple=1, phone=1, is=2, an=1}
{a=1, apple=2, phone=1, is=2, an=1}
Upvotes: 0
Reputation: 21975
You can use a HashMap
with the words being the Key
and the occurences the Value
:
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
String[] myPhrase = keyboard.nextLine().split(" ");
HashMap<String, Integer> myWordsCount = new HashMap<String, Integer>();
for (String s : myPhrase){
if (myWordsCount.containsKey(s)) myWordsCount.replace(s, myWordsCount.get(s) + 1);
else myWordsCount.put(s, 1);
}
System.out.println(myWordsCount);
}
Output
One two three four and again three and four
{four=2, and=2, One=1, again=1, two=1, three=2}
Upvotes: 4