From the documentation you linked:
The Counter class is similar to bags or multisets in other languages.
Java does not have a Multiset class or equivalent. Guava has a Multiset collection that does exactly what you want.
In pure Java, you can use Map<T, Integer> and the new merge method:
final Map<String, Integer> counts = new HashMap<>(); counts.merge("Test", 1, Integer::sum); counts.merge("Test", 1, Integer::sum); counts.merge("Other", 1, Integer::sum); counts.merge("Other", 1, Integer::sum); counts.merge("Other", 1, Integer::sum); System.out.println(counts.getOrDefault("Test", 0)); System.out.println(counts.getOrDefault("Other", 0)); System.out.println(counts.getOrDefault("Another", 0));
Output:
2 3 0
You can wrap this behavior in a class in a few lines of code:
public class Counter<T> { final Map<T, Integer> counts = new HashMap<>(); public void add(T t) { counts.merge(t, 1, Integer::sum); } public int count(T t) { return counts.getOrDefault(t, 0); } }
Use this:
final Counter<String> counts = new Counter<>(); counts.add("Test"); counts.add("Test"); counts.add("Other"); counts.add("Other"); counts.add("Other"); System.out.println(counts.count("Test")); System.out.println(counts.count("Other")); System.out.println(counts.count("Another"));
Output:
2 3 0
source share