~/ learn/ comp-308/ cards/ Set & Map
1 of 5

Word-count with a HashMap and getOrDefault

Word-count with a HashMap and getOrDefault

Answer

Map<String,Integer> counts = new HashMap<>(); for (String w : text) counts.put(w, counts.getOrDefault(w, 0) + 1);

getOrDefault(w, 0) returns the current count or 0 for an unseen word; +1 and put writes the new count back. This is the standard Map counting idiom; counts.merge(w, 1, Integer::sum) does the same.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/4921f4ce-0cf6-45be-82ed-9433d4ccdf22/flashcard utf-8 LF