Search code examples
javaarraylisthashmapword-count

How do I count the occurrences of each word in each of sentences stored in arraylists?


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));

Solution

    1. Lets call your ArrayList<String> list.
    2. Let's make a list list2 of String[] 3, Split Sentences to the array.
    3. Count occurrences

    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());
    }