Calculating frequency of each word in a sentence in java

前端 未结 19 1970
夕颜
夕颜 2020-11-29 10:15

I am writing a very basic java program that calculates frequency of each word in a sentence so far i managed to do this much

import java.io.*;

class Linked         


        
相关标签:
19条回答
  • 2020-11-29 11:15

    Use a map with word as a key and count as value, somthing like this

        Map<String, Integer> map = new HashMap<>();
        for (String w : words) {
            Integer n = map.get(w);
            n = (n == null) ? 1 : ++n;
            map.put(w, n);
        }
    

    if you are not allowed to use java.util then you can sort arr using some sorting algoritm and do this

        String[] words = new String[arr.length];
        int[] counts = new int[arr.length];
        words[0] = words[0];
        counts[0] = 1;
        for (int i = 1, j = 0; i < arr.length; i++) {
            if (words[j].equals(arr[i])) {
                counts[j]++;
            } else {
                j++;
                words[j] = arr[i];
                counts[j] = 1;
            }
        }
    

    An interesting solution with ConcurrentHashMap since Java 8

        ConcurrentMap<String, Integer> m = new ConcurrentHashMap<>();
        m.compute("x", (k, v) -> v == null ? 1 : v + 1);
    
    0 讨论(0)
提交回复
热议问题