使用以单词为键的地图并将其计为值,像这样
Map<String, Integer> map = new HashMap<>(); for (String w : words) { Integer n = map.get(w); n = (n == null) ? 1 : ++n; map.put(w, n); }如果不允许使用java.util,则可以使用一些排序算法对arr进行排序,并执行此操作
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; } }从Java 8开始使用ConcurrentHashMap的有趣解决方案
ConcurrentMap<String, Integer> m = new ConcurrentHashMap<>(); m.compute("x", (k, v) -> v == null ? 1 : v + 1);


