I have an arraylist
that holds each line of a document for example-
list.add("I like to play pool")
list.add("How far can you run")
list.add("Do you like fanta because I like fanta")
I want to be able to go through each sentence stored in the arrayList
and count the occurrence of each word in each of the sentences, can anyone help me?
EDIT This is what I tried but it only tells me the occurrence of EACH sentence. I need it to be able to count the words for each sentence.
Set<String> unique = new HashSet<String>(list);
for (String key : unique) {
System.out.println(key + ": " + Collections.frequency(list, key));
ArrayList<String> list
.The code:
ArrayList<String> list = new ArrayList<>();
//add sentences here
list.add("My first sentence sentence");
list.add("My second sentence1 sentence1");
ArrayList<String[]> list2 = new ArrayList<>();
for (String s : list) { list2.add(s.split(" "));};
for (String[] s : list2) {
Map<String, Integer> wordCounts = new HashMap<String, Integer>();
for (String word : s) {
Integer count = wordCounts.get(word);
if (count == null) {
count = 0;
}
wordCounts.put(word, count + 1);
}
for (String key : wordCounts.keySet()) {
System.out.println(key + ": " + wordCounts.get(key).toString());
}