javastringapache-commons

How to count duplicates in an array of strings?


How do I partition a String to extract all the words/terms that occur in it and count how many times each occurs? For example let: String q = "foo bar foo" I want a DS {<foo,2>, <bar,1>}. This is the least verbose code I code come with*. Faults or less verbose alternatives?

String[] split = q.toString().split("\\s");
        Map<String, Integer> terms = new HashMap<String, Integer>();

        for (String term : split) {
            if(terms.containsKey(term)){
                terms.put(term, terms.get(term)+1);
            }
        }

(haven't compiled it)


Solution

  • Modified code:

    String[] split = q.toString().split("\\s");
    Map<String, Integer> terms = new HashMap<String, Integer>();
    
    for (String term : split) {
        int score = 0;
        if(terms.containsKey(term)){
            score = terms.get(term);
        }
    
        terms.put(term, score +1);
    }
    

    PS: Untested.