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.